<h1 id="introduction">Introduction</h1>
<p>Templates are a central feature of D, giving you powerful compile-time code generation abilities that'll make your code cleaner, more flexible and even more efficient. They are used everywhere in <a href="http://www.dlang.org/phobos/">Phobos</a> --- D standard library --- and therefore any D user should know about them. But, based on C++ templates as they are, D templates can be a bit daunting at first. The <a href="http://www.dlang.org">D Programming Language</a> website's <a href="http://www.dlang.org/template.html">documentation</a> is a good start, though its description of templates is spread among many different files and (as it's a language reference) its material doesn't so much <em>teach</em> you how to use templates as <em>show</em> you their syntax and semantics.</p>
<p>This document aims to be a kind of tutorial on D templates, to show the beginning D coder what can be achieved with them. When I was using C++, I remember <em>never</em> using templates for more than <em>containers-of-T</em> stuff, and considered Boost-level<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a> metaprogramming the kind of code I could never understand, never mind produce. Well, D's sane syntax for templates and nifty features such as <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>, <code class="sourceCode d"><span class="kw">alias</span></code> or tuples cured me of that impression. I hope this document will help you, too.</p>
<h2 id="whats-in-this-document">What's in This Document</h2>
<p><a href="#basics">The first part</a> deals with the very basics: how to declare and instantiate a template, the standard `building blocks' you'll use in almost all your templates, along with <a href="#function-templates">function</a>, <a href="#struct-templates">struct</a> and <a href="#class-templates">class</a> templates. Throughout the text, examples will present applications of these concepts.</p>
<p><a href="#some-more-advanced-considerations">The second part</a> is about more advanced topics a D template user will probably use, but not on a daily basis, like <a href="#constraints">template constraints</a>, <a href="#mixin-templates">mixin templates</a> or <a href="#operator-overloading">operator overloading</a>.</p>
<p><a href="#around-templates">The third part</a> presents other metaprogramming tools: <a href="#string-mixins">string mixins</a>, <a href="#compile-time-function-evaluation">compile-time function evaluation</a>, and <a href="#traits">__traits</a>. These are seen from a template-y point of view: how they can interact with templates and what you can build with them in conjunction with templates.</p>
<p><a href="#examples">The fourth part</a> presents more developed examples of what can be done with templates, based on real needs I had at some time and that could be fulfilled with templates.</p>
<p>Finally, an appendix on the <a href="#the-is-expression">ubiquitous is expression</a> and another giving <a href="#resources-and-further-reading">resources</a> and further reading advice complete this document.</p>
<h2 id="conventions">Conventions</h2>
<p>To make this document more easily readable, I'll use standard coding books conventions, by highlighting parts of the text. Mainly, in this doc:</p>
<ul>
<li>D keywords will be marked like this: <code class="sourceCode d"><span class="dt">int</span></code>, <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>, <code class="sourceCode d">__traits</code> (these will be colored or not, depending on what was used to generate the document).</li>
<li>Symbols and names used in code samples and cited in the text will be written like this: <code>myFunc</code>, <code>flatten</code>.</li>
<li>internal links will be like <a href="#introduction">this</a>.</li>
<li>external links will be like <a href="http://www.dlang.org">this</a>.</li>
<li>Syntax-highlighted code samples are shown like this:</li>
</ul>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="co">/**</span>
<span class="co"> * This is a doc comment.</span>
<span class="co"> */</span>
<span class="kw">module</span> intro;

<span class="kw">import</span> std.stdio;

<span class="dt">void</span> main()
{
    <span class="dt">int</span> times = <span class="dv">10</span>;
    <span class="co">// This is a comment</span>
    <span class="kw">foreach</span>(i; <span class="dv">0</span>..times)
        writeln(<span class="st">&quot;Hello, Word!&quot;</span>);
}</code></pre></td></tr></table>
<p>Numbered lines will be used only when necessary.</p>
<p>I will sometimes make a little explanatory detour, discussing a small piece of info too small to be in its own section but of interest to the reader nonetheless. These will be marked so:</p>
<blockquote>
<p><strong>Semi-Literate Programming.</strong> Most code samples presented in this document will compile with a reasonably recent D compiler. In the <code>utils</code> directory, there is a small D script called <code>codesamples.d</code> that extracts code samples from the mardkdown files.</p>
</blockquote>
<blockquote>
<p>Samples with a <code class="sourceCode d"><span class="kw">module</span> name;</code> declaration will be extracted, a file called <code>name.d</code> will be created and compiled (possibly with a stub <code class="sourceCode d">main()</code> if none exists). The previous code sample creates a file called <code>intro.d</code> and so on. The compilation results are put in a file called <code>result.txt</code>. Samples that depend on other samples just import them (yeah for D modularity, no need for specific mark-up to weave code together). Samples with a name ending in <code>_error</code> will <em>not</em> compile, as expected: they are there to show errors, mistakes and gotchas. Anonymous samples are not extracted: I use them to show small snippets not intended to stand by themselves, or just to show D-ish pseudocode.</p>
</blockquote>
<blockquote>
<p>All in all, you can see this entire document as a gigantic D package, describing hundreds of small modules.</p>
</blockquote>
<p>Finally, some sections in this doc are not finished yet. The sections I consider unfinished will contain this:</p>
<blockquote>
<p><strong>Unfinished.</strong> Hey, now I've added a Thanks section. But as long as I'm adding new parts in the document, new appendices, and new section, this intro will not be finished.</p>
</blockquote>
<p>I probably forgot some 'unfinished' tags, do not hesitate to tell me so.</p>
<h2 id="how-to-get-this-document">How to Get This Document</h2>
<p>This document is just a markdown file <a href="http://github.com/PhilippeSigaud/D-templates-tutorial">hosted on Github</a>. Don't hesitate to fork it or (even better for me) to make pull requests! For those of you reading this on paper, the address is:</p>
<p><a href="https://github.com/PhilippeSigaud/D-templates-tutorial">https://github.com/PhilippeSigaud/D-templates-tutorial</a></p>
<h2 id="thanks">Thanks</h2>
<p>As soon as I publicly released this document, D community members gave me help, suggestions, corrections, and code samples. This is cool to see a D network emerge and people participating in common projects. The following people helped me:</p>
<p>Craig Dillabaugh, Andrej Mitrovic, Justin Whear, Zachary Lund, Jacob Carlborg, Timon Gehr, Simen Kjaeras, Andrei Alexandrescu, Bjorn Lietz-Spendig.</p>
<p>Thanks guys!</p>
<h1 id="basics">Basics</h1>
<h2 id="why-templates">Why Templates?</h2>
<p>Here you are, reading a book-size document on D templates. But why should you be interested in templates? Let say you have this wonderful tree struct:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> basicTree1;

<span class="kw">struct</span> Tree {
    <span class="dt">int</span> value;
    Tree[] children;
    
    <span class="dt">size_t</span> size() {
        <span class="dt">size_t</span> s = <span class="dv">1</span>;
        <span class="kw">foreach</span>(child; children)
            s += child.size();
        <span class="kw">return</span> s;
    }
    
    <span class="dt">bool</span> isLeaf() @property {
        <span class="kw">return</span> children.<span class="dt">length</span> == <span class="dv">0</span>;
    }
}</code></pre>
<p>Which is used like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingBasicTree1;

<span class="kw">import</span> basicTree1;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> tree = Tree(<span class="dv">0</span>, [Tree(<span class="dv">1</span>), Tree(<span class="dv">2</span>, [Tree(<span class="dv">3</span>), Tree(<span class="dv">4</span>), Tree(<span class="dv">5</span>)])]);
    <span class="kw">assert</span>(!tree.isLeaf);
    <span class="kw">assert</span>(tree.size() == <span class="dv">6</span>);
}</code></pre>
<p>All is well and good, this is a nice basic <code class="sourceCode d"><span class="dt">int</span></code>-holding n-ary tree. But what if, after some time, you need a <code class="sourceCode d"><span class="dt">float</span></code>-holding one? No problem, this can be coded easily, with a bit of copy-pasting. First, we change <code>Tree</code> to <code>IntTree</code> and then create a <code>FloatTree</code> node:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> basicTree2;

<span class="kw">struct</span> IntTree {
    <span class="dt">int</span> value;
    IntTree[] children;
    
    <span class="dt">size_t</span> size() {
        <span class="dt">size_t</span> s = <span class="dv">1</span>;
        <span class="kw">foreach</span>(child; children)
            s += child.size();
        <span class="kw">return</span> s;
    }
    
    <span class="dt">bool</span> isLeaf() @property {
        <span class="kw">return</span> children.<span class="dt">length</span> == <span class="dv">0</span>;
    }
}

<span class="kw">struct</span> FloatTree {
    <span class="dt">float</span> value;
    FloatTree[] children;
    
    <span class="dt">size_t</span> size() {
        <span class="dt">size_t</span> s = <span class="dv">1</span>;
        <span class="kw">foreach</span>(child; children)
            s += child.size();
        <span class="kw">return</span> s;
    }
    
    <span class="dt">bool</span> isLeaf() @property {
        <span class="kw">return</span> children.<span class="dt">length</span> == <span class="dv">0</span>;
    }
}</code></pre>
<p>But that's a lot of code duplication: the only changes are the types of <code>value</code> and <code>children</code>, which become a <code class="sourceCode d"><span class="dt">float</span></code> and <code>FloatTree</code> instead of an <code class="sourceCode d"><span class="dt">int</span></code> and <code>IntTree</code>. What a waste! And what if we need another tree, for example holding functions (a tree of callbacks, say)? There must be a better way.</p>
<p>Let's observe the previous code. What we need here is a way to produce code by generating different tree types, injecting the type for <code>value</code> as user-defined input. It's a bit like a function: pushing parameters and getting a result. Let's imagine some code with a placeholder, let's call it <code>Type</code>, to represent the type of <code>value</code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">struct</span> Tree {
    Type value;
    Tree[] children;
    
    <span class="dt">size_t</span> size() {
        <span class="dt">size_t</span> s = <span class="dv">1</span>;
        <span class="kw">foreach</span>(child; children)
            s += child.size();
        <span class="kw">return</span> s;
    }
    
    <span class="dt">bool</span> isLeaf() @property {
        <span class="kw">return</span> children.<span class="dt">length</span> == <span class="dv">0</span>;
    }
}</code></pre>
<p>But here <code>Type</code> is a symbol introduced without warning in the struct scope. If you try to compile that code, the compiler will rightfully complain and ask you 'where does <code>Type</code> come from?'. With functions, parameters are introduced in a parameter list(!) that will push them into the following scope, the function body. That's what we want here. We should tell the compiler that <code>Type</code> is our placeholder, to be provided latter on. Let's continue with our imaginary syntax here:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> genericTree;

<span class="kw">struct</span> Tree(Type) {
    Type value;
    Tree[] children;
    
    <span class="dt">size_t</span> size() {
        <span class="dt">size_t</span> s = <span class="dv">1</span>;
        <span class="kw">foreach</span>(child; children)
            s += child.size();
        <span class="kw">return</span> s;
    }
    
    <span class="dt">bool</span> isLeaf() @property {
        <span class="kw">return</span> children.<span class="dt">length</span> == <span class="dv">0</span>;
    }
}</code></pre>
<p>See how I introduced <code>Type</code> in a (one-element) parameter list, right after <code>Tree</code>? Ideally, this is what a struct definition abstracted on the type of <code>value</code> should look like, right? A sort of... recipe to be used to generate the <code>Tree</code> we need.</p>
<p>Look no further, the previous definition is standard D for a struct template! You can compile it and use it to your heart content (see the next chapters to do that).</p>
<p>That's the essence of templates: writing some code, seeing way to abstract it on certain items (types, symbols, numbers, the possibility are numerous) and defining such a generic recipe, for further perusal.</p>
<h2 id="what-is-a-template">What is a Template?</h2>
<p>In the next chapters, you'll see how to define <a href="#function-templates">function</a>, <a href="#struct-templates">struct</a> and <a href="#class-templates">class</a> templates. The nifty syntax demonstrated just before is a special case for these constructs. It's a simplified version of the full template declaration syntax, which we will see in the next section.</p>
<p>But before that, I'd like to introduce what a template <em>really</em> is, because this definition is the most fundamental of the whole document. As I said, a template is a way to define a blueprint to generate some code, be it a class definition, a function or... what? What could be the most abstract unit of code?</p>
<p>Let us say you have a wonderful piece of code, full of function definitions, structs and their methods, new symbols, and so on. This piece of code offer a few entry points for further parameterization: some types, some symbols could be abstracted away and put into a template parameter list.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// Could be parameterized on Type, as seen before</span>
<span class="kw">struct</span> Tree { ... } 

<span class="co">// Could be parameterized on the Tree type also</span>
<span class="co">// And maybe on f?</span>
Tree mapOnTree(Tree input, Tree <span class="kw">delegate</span>(Tree) f) { ... }

<span class="dt">void</span> printTree(Tree input) { ... }

<span class="co">// What about defining a different TreeArray for all possible Trees?</span>
<span class="kw">alias</span> TreeArray = Tree[];</code></pre>
<p>But where is the basic unit to hold this code? Well, a code block of course, or a <em>scope</em>. Ideally, we would like a way to group all the previous declaration into one unit, with the same parameter list:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// scope?</span>
(Type)
{
    <span class="kw">struct</span> Tree { <span class="co">/* using Type here */</span>}
    Tree mapOnTree(Tree input, Tree <span class="kw">delegate</span>(Tree) f) { <span class="co">/* here also */</span> }
    <span class="dt">void</span> printTree(Tree input) { <span class="co">/* the same */</span> }
    <span class="kw">alias</span> TreeArray = Tree[]; <span class="co">// You get it</span>
}</code></pre>
<p>Since we will need to 'call' it to produce some code (a bit like you'd call a function), this code block needs a name. And then, we just need to tell the compiler: 'here, this is a blueprint'. The D keyword for that is (you got it) <code class="sourceCode d"><span class="kw">template</span></code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> MyDefs(Type)
{
    <span class="kw">struct</span> Tree {...}
    Tree mapOnTree(Tree input, Tree <span class="kw">delegate</span>(Tree) f) {...}
    <span class="dt">void</span> printTree(Tree input) {...}
    <span class="kw">alias</span> TreeArray = Tree[];
}</code></pre>
<p>Here you are. This is what a template is, at its core: a named, parameterized, code block, ready to be instantiated just for you.</p>
<h2 id="template-declarations">Template Declarations</h2>
<p>Here is the syntax for a template declaration:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> templateName(list, of, parameters)
{
  <span class="co">// Some syntactically correct declarations here</span>
  <span class="co">// The arguments are accessible inside the template scope.</span>
}</code></pre>
<p><code>templateName</code> is your usual D identifier and the list of parameters is a comma-separated list of zero or more template parameters. These can be:</p>
<dl>
<dt>Types (<code>identifier</code>)</dt>
<dd><p>An <code>identifier</code> alone by itself is considered a type name. The common D style is to use identifiers beginning with a capital letter (<code>Range</code>, <code>Rest</code>), as for any user-defined types. Many D templates use the C++ tradition of one-capital-letter names for types, starting from <code>T</code> (<code>U</code>, <code>V</code>, ...). Do not feel constrained by this, use what makes your templates most easy to understand.</p>
</dd>
<dt>Aliases (<code class="sourceCode d"><span class="kw">alias</span> identifier</code>)</dt>
<dd><p>You declare them with <code class="sourceCode d"><span class="kw">alias</span> identifier</code>. They will capture not types but <em>symbols</em>: variable names, class <em>names</em>, even other template names. They will also accept many compile-time literals: strings, arrays, function literals, ... Mostly, if you need a widely-accepting template, use an <code>alias</code> parameter. Note that they will <em>not</em> accept built-in types as arguments, however, since <code>int</code> is not a valid identifier in D (it's a keyword).</p>
</dd>
<dt>Literal values (<code>typeName identifier</code>)</dt>
<dd><p>They are all declared like this: <code>typeName identifier</code>. Literal values can be integral values (<code class="sourceCode d"><span class="dt">int</span></code>, <code class="sourceCode d"><span class="dt">ulong</span></code>, ...), <code class="sourceCode d"><span class="kw">enum</span></code>-based, strings, <code class="sourceCode d">chars</code>, floating-point values or boolean values. Any expression that can be evaluated at compile-time is OK. For example : <code class="sourceCode d"><span class="dt">int</span> depth</code> or <code class="sourceCode d"><span class="dt">string</span> name</code>.</p>
</dd>
<dt>Template parameters tuples (<code>identifier...</code>)</dt>
<dd><p>The syntax is <code>identifier...</code> (yes, three dots) and the tuple must be the last parameter of a template. Template parameters tuples will capture under one identifier <em>an entire list of template parameters</em> (types, names, literals, ...). These tuples will store any template argument you will throw at them. If no argument is passed, you will just get an empty, zero-length, tuple. Really, as they can deal with types as well as symbols, these tuples are a bit of a mongrel type but they are wonderfully powerful and easy to use, as you will see in section <a href="#template-tuple-parameters">Tuples</a>.</p>
</dd>
</dl>
<p>Of those, types and aliases are the most common, while floating point values are fairly rare: their use as arguments for compile-time calculations have been superseded by D's Compile-Time Function Evaluation, aka <a href="#ctfe">CTFE</a>. You'll see different uses of these parameters in this document.</p>
<p>Note that pointers, arrays, objects (instantiated classes), structs or functions are not part of this list. But as I said, alias parameters allow you to capture and use array, class, function or struct <em>names</em> and then access their capacities.</p>
<blockquote>
<p><strong>Aliases, Symbols and Names.</strong> There is big difference between built-in types like <code class="sourceCode d"><span class="dt">int</span></code> or <code class="sourceCode d"><span class="dt">double</span>[<span class="dv">3</span>]</code> and user-defined types. A user-defined type, say a class called <code>MyClass</code>, is a type name. So, it's <em>both</em> a type (the class <code>MyClass</code>, accepted by type templates arguments) and a name, a symbol (<code>MyClass</code>, accepted by <code>alias</code> template parameters). On the other hand, <code class="sourceCode d"><span class="dt">int</span></code>, being a D keyword is not a symbol nor a name. It's just a type. You cannot pass it to an alias template parameter.</p>
</blockquote>
<p>The template body can contain any standard D declarations: variable, function, class, interface, other templates, alias declarations,... The only exception I can think of is declaring a <code>module</code>, as this is done at the top-level scope.</p>
<blockquote>
<p><strong>Syntax and Semantics.</strong> Code inside a <code class="sourceCode d"><span class="kw">template</span></code> declaration only has to be syntactically correct D code (that is: code that looks like D code). The semantics are not checked until instantiation. That means you can code happily, writing templates upon templates and the compiler won't bat an eye if you do not exercise your templates by instantiating them.</p>
</blockquote>
<p>Inside the template body, the parameters are all accessible as placeholders for the future arguments. Also, the template's own name refers to its current instantiation when the code is generated. This is mostly used in <a href="#struct-templates">struct templates</a> and <a href="#class-templates">class templates</a>.</p>
<p>Here are some template declaration examples:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> declaration;

<span class="kw">template</span> ArrayOf(T) <span class="co">// T is a type</span>
{
    <span class="kw">alias</span> ArrayType   = T[];
    <span class="kw">alias</span> ElementType = T;
}

<span class="kw">template</span> Transformer(From, To) <span class="co">// From and To are types, too</span>
{
    To transform(From from)
    {
        <span class="kw">import</span> std.conv;
        <span class="kw">return</span> to!(To)(from);
    }

    <span class="kw">class</span> Modificator
    {
        From f;
        To t;
        <span class="kw">this</span>(From f) { <span class="co">/*...*/</span> }
    }
}

<span class="kw">template</span> nameOf(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> <span class="dt">string</span> name = a.<span class="dt">stringof</span>; <span class="co">// enum: manifest constant</span>
                                   <span class="co">// determined at compile-time.</span>
                                   <span class="co">// See below.</span>
}

<span class="kw">template</span> ComplicatedOne(T, <span class="dt">string</span> s, <span class="kw">alias</span> a, <span class="dt">bool</span> b, <span class="dt">int</span> i)
{ <span class="co">/* some code using T, s, a, b and i */</span> }

<span class="kw">template</span> Minimalist() {} <span class="co">// Zero-parameter template declaration.</span>

<span class="kw">template</span> OneOrMore(FirstType, Rest...) <span class="co">// Rest is a tuple.</span>
{ <span class="co">/*...*/</span> }

<span class="kw">template</span> ZeroOrMore(Types...) <span class="co">// Types is a tuple.</span>
{ <span class="co">/*...*/</span> }

<span class="kw">template</span> Multiple(T)     { <span class="co">/*...*/</span> } <span class="co">// One arg version.</span>
<span class="kw">template</span> Multiple(T,U)   { <span class="co">/*...*/</span> } <span class="co">// Two args,</span>
<span class="kw">template</span> Multiple(T,U,V) { <span class="co">/*...*/</span> } <span class="co">// and three.</span></code></pre></td></tr></table>
<p>The full syntax for template declarations is slightly more complex, I'll introduce more of it in the next sections. You'll see for example type restrictions in section <a href="#templates-specializations">Templates Specializations</a>, default values in section <a href="#default-values">Default Values</a>, instantiation constraints in <a href="#constraints">Template Constraints</a>, and more on tuples in section <a href="#template-tuple-parameters">tuples</a>.</p>
<p>There is a limitation that's interesting to keep in mind: templates can be declared in almost any scope, except inside a (regular) function.</p>
<blockquote>
<p><strong>enum.</strong> In the previous code, see line 27? It defines a <code class="sourceCode d"><span class="dt">string</span></code> called <code>name</code> as a member of <code>nameOf</code>. The <code class="sourceCode d"><span class="kw">enum</span></code> placed right before means <code>name</code> is a compile-time constant. You can see it as a kind of storage class, in the line of <code class="sourceCode d"><span class="kw">immutable</span></code> or <code class="sourceCode d"><span class="kw">const</span></code>, one that means the value is totally defined and fixed at runtime. You'll see numerous examples of <code class="sourceCode d"><span class="kw">enum</span></code> in this document.</p>
</blockquote>
<h2 id="instantiating-a-template">Instantiating a Template</h2>
<h3 id="syntax">Syntax</h3>
<p>To instantiate a template, use the following syntax:</p>
<pre class="sourceCode d"><code class="sourceCode d">templateName!(list, of, arguments)</code></pre>
<p>Note the exclamation point (<code>!</code>) before the comma-separated argument list. That's what differentiate template arguments lists from standard (funtion) argument lists. If both are present (for function templates), we will use:</p>
<pre><code>templateName!(template, argument, list)(runtime, agument, list)</code></pre>
<p>There is a small trick to get a shorter instantiation syntax: if the argument list contains only one argument with a length of one token, you can drop the parenthesis, like this:</p>
<pre class="sourceCode d"><code class="sourceCode d">templateName!argument</code></pre>
<p>So, these are all valid template instantiations:</p>
<pre class="sourceCode d"><code class="sourceCode d">Template!(<span class="dt">int</span>)
Template!<span class="dt">int</span>

Template!(<span class="st">&quot;string arg&quot;</span>)
Template!<span class="st">&quot;string arg&quot;</span>

map!(foo)(range); <span class="co">// foo is a symbol, capture by an alias.</span>
                  <span class="co">// range is a runtime argument.</span>
map!foo(range);   <span class="co">// ditto</span>

<span class="co">// But:</span>
Multiple!(<span class="dt">int</span>, <span class="dt">double</span>)
<span class="co">// And not:</span>
<span class="co">// Multiple!int, double //??</span></code></pre>
<h3 id="templates-as-template-arguments">Templates as Template Arguments</h3>
<p>Arguments can themselves be the result of another template instantiation. If a template returns a type upon instantiation, it's perfectly OK to use it inside another template argument list. In this document you'll regularly see Matrioshka calls like this: <code>firstTemp!(secondTempl!(Arguments), OtherArguments)</code>.</p>
<h3 id="selecting-among-declarations">Selecting among Declarations</h3>
<p>The compiler will have a look at the declarations (if more than one template was declared with the called name) and select the one with the correct number of arguments and the correct types to instantiate. If more than one template can be instantiated, it will complain and stop there (though, have a look on <a href="#templates-specializations">template specializations</a> and <a href="#constraints">template constraints</a>.</p>
<h3 id="effect-of-instantiation">Effect of Instantiation</h3>
<p>When you instantiate a template, the global effect is that a new named scope (code block) is created at the template declaration scope. The name of this new scope is the template name with its argument list: <code>templateName!(args)</code>. Inside this block, the parameters are now 'replaced' with the corresponding arguments (storage classes get applied, variables are initialized, ...). Here's what possible instantiations of the previous templates might look like:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> instantiation;
<span class="kw">import</span> declaration;

<span class="dt">void</span> main()
{
    ArrayOf!(<span class="dt">int</span>).ArrayType myArray;

     <span class="co">// From is an alias for the type double</span>
     <span class="co">// To for the type int</span>
    <span class="kw">alias</span> transfo = Transformer!(<span class="dt">double</span>,<span class="dt">int</span>);

    <span class="kw">struct</span> MyStruct { <span class="co">/*...*/</span> }

    <span class="co">// &quot;MyStruct&quot; is a identifier -&gt; captured by alias</span>
    <span class="kw">auto</span> name = nameOf!(MyStruct).name;

    <span class="kw">alias</span> complicatedExample =
    ComplicatedOne!( <span class="dt">int</span>[]   <span class="co">// a type</span>
                   , <span class="st">&quot;Hello&quot;</span> <span class="co">// a string literal</span>
                   , ArrayOf <span class="co">// a name</span>
                   , <span class="kw">true</span>    <span class="co">// a boolean literal</span>
                   , <span class="dv">1</span>+<span class="dv">2</span>     <span class="co">// calculated to be the integral &#39;3&#39;.</span>
                   );

    <span class="kw">alias</span> min1 = Minimalist!(); <span class="co">// No argument</span>

    <span class="co">// FirstType is &#39;int&#39;</span>
    <span class="co">// Rest is &#39;double,string,&quot;abc&quot;&#39;</span>
    <span class="kw">alias</span> oneOrMore =
          OneOrMore!( <span class="dt">int</span>
                    , <span class="dt">double</span>, <span class="dt">string</span>, <span class="st">&quot;abc&quot;</span>
                    );

    <span class="co">// Types is a 1-element tuple: (int)</span>
    <span class="kw">alias</span> zero1 = ZeroOrMore!(<span class="dt">int</span>);
    <span class="co">// Types is (int,double,string)</span>
    <span class="kw">alias</span> zero2 = ZeroOrMore!(<span class="dt">int</span>,<span class="dt">double</span>,<span class="dt">string</span>);
    <span class="co">// Types is the empty tuple: ()</span>
    <span class="kw">alias</span> zero3 = ZeroOrMore!();

    <span class="co">// Selects the one-arg version</span>
    <span class="kw">alias</span> mult1 = Multiple!(<span class="dt">int</span>);
    <span class="co">// The three args version.</span>
    <span class="kw">alias</span> mult2 = Multiple!(<span class="dt">int</span>,<span class="dt">double</span>,<span class="dt">string</span>);
    <span class="co">// Error! No 0-arg version</span>
    <span class="co">//alias mult3 = Multiple!();</span>
}</code></pre>
<p>Outside the scope (that is, where you put the template instantiation in your own code), the internal declarations are accessible by fully qualifying them:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> internaldeclarations1;
<span class="kw">import</span> declaration;

<span class="co">// ArrayType is accessible (it&#39;s int[])</span>
<span class="co">// array is a completly standard dynamic array of ints.</span>
ArrayOf!(<span class="dt">int</span>).ArrayType array;
ArrayOf!(<span class="dt">int</span>).ElementType element; <span class="co">// the same, element is an int.</span>

<span class="dt">void</span> main()
{
    <span class="co">// the transform function is accessible. Instantiated like this,</span>
    <span class="co">// it&#39;s a function from double to string.</span>
    <span class="kw">auto</span> s = Transformer!(<span class="dt">double</span>,<span class="dt">string</span>).transform(<span class="fl">3.14159</span>);
    <span class="kw">assert</span>(<span class="kw">is</span>(<span class="dt">typeof</span>(s) == <span class="dt">string</span>)); <span class="co">// s is a string</span>
}</code></pre>
<p>Obviously, using templates like this, with their full name, is a pain. The nifty D <code class="sourceCode d"><span class="kw">alias</span></code> declaration is your friend:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> internaldeclarations2;
<span class="kw">import</span> declaration;

<span class="kw">alias</span> DtoS = Transformer!(<span class="dt">double</span>, <span class="dt">string</span>);

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> s = DtoS.transform(<span class="fl">3.14159</span>);
    <span class="kw">auto</span> m = <span class="kw">new</span> DtoS.Modificator(<span class="fl">1.618</span>); <span class="co">// DtoS.Modificator is a class</span>
                                          <span class="co">// storing a double and a string.</span>
}</code></pre>
<p>You must keep in mind that instantiating a template means generating code. Using different arguments at different places in your code will instantiate <em>as many differently named scopes</em>. This is a major difference with <em>generics</em> in languages like Java or C#, where generic code is created only once and type erasure is used to link all this together. On the other hand, instantiating the same template, with the same arguments, will create only one piece of code.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> differentinstantiations;
<span class="kw">import</span> declaration;

<span class="kw">alias</span> StoD = Transformer!(<span class="dt">string</span>,<span class="dt">double</span>);
<span class="kw">alias</span> DtoS = Transformer!(<span class="dt">double</span>,<span class="dt">string</span>);
<span class="kw">alias</span> StoI = Transformer!(<span class="dt">string</span>,<span class="dt">int</span>);
<span class="co">// Now we can use three different functions and three different classes.</span></code></pre>
<blockquote>
<p><strong>void.</strong> Note that <code class="sourceCode d"><span class="dt">void</span></code> is a valid D type and, as such, a possible template argument for a type parameter. Take care: many templates make no sense when <code class="sourceCode d"><span class="dt">void</span></code> is used as a type. In the following sections and in the appendix, you'll see ways to restrict arguments to only certain types.</p>
</blockquote>
<h2 id="template-building-blocks">Template Building Blocks</h2>
<p>Up to now, templates may not seem that interesting to you, even with a simple declaration and instantiation syntax. But wait! D introduced a few nifty tricks that both simplify and greatly expand template uses. This section will introduce you to your future best friends, the foundations on which your templates will be built.</p>
<h3 id="the-eponymous-trick">The Eponymous Trick</h3>
<p>If a template declares a symbol with the same name (greek: <em>epo-nymous</em>) as the enclosing template, that symbol is assumed to be referred to when the template is instantiated. This one is pretty good to clean your code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> pair;

<span class="kw">template</span> pair(T)
{
    <span class="co">// template &#39;pair&#39; declares only a &#39;pair&#39; member</span>
    T[] pair(T t) { <span class="kw">return</span> [t,t];}
}

<span class="kw">auto</span> array = pair!(<span class="dt">int</span>)(<span class="dv">1</span>);  <span class="co">// no need to do pair!(int).pair(1)</span></code></pre>
<p>or:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nameof1;

<span class="kw">template</span> nameOf(<span class="kw">alias</span> name)
{
    <span class="kw">enum</span> <span class="dt">string</span> nameOf = name.<span class="dt">stringof</span>;
}

<span class="kw">struct</span> Example { <span class="dt">int</span> i;}

<span class="dt">void</span> main()
{
    Example example;

    <span class="kw">auto</span> s1 = nameOf!(Example);
    <span class="kw">auto</span> s2 = nameOf!(example);

    <span class="kw">assert</span>(s1 == <span class="st">&quot;Example&quot;</span>);
    <span class="kw">assert</span>(s2 == <span class="st">&quot;example&quot;</span>);
}</code></pre>
<p>There used to be a limitation in that the eponymous trick worked <em>only</em> if you defined one (and only one) symbol. Even if the other symbols were private, they would break the eponymous substitution. This was changed recently (Fall 2012) and now, we can do:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> record;

<span class="kw">template</span> Record(T, U, V)
{
    <span class="kw">import</span> std.typecons: Tuple, tuple;

    <span class="co">// The real work is done here</span>
    <span class="co">// Use as many symbols as you need.</span>
    <span class="kw">alias</span> Tuple!(T,U) Pair;
    <span class="kw">alias</span> Pair[V] AssocArray;
    <span class="kw">alias</span> AssocArray[] Record;
}</code></pre>
<p>Note that in this case, the eponymous member is an alias, whereas it was a function or a manifest constant (an <code class="sourceCode d"><span class="kw">enum</span></code>) in previous examples. As was already said, any member with the same name will do.</p>
<p>And then, to use <code>Record</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_record;
<span class="kw">import</span> record;

Record!(<span class="dt">int</span>,<span class="dt">string</span>,<span class="dt">double</span>[]) recordslist;
<span class="co">/* ... */</span></code></pre>
<p>Although, in this case, the eponymous member hides the other members: <code>Pair</code> and <code>AssocArray</code> cannot be accessed any more. That seems logical, since if you use the eponymous trick, it's to provide a simplified interface to your users.</p>
<h3 id="inner-alias">Inner alias</h3>
<p>A common use for templates is to do some type magic: deducing types, assembling them in new way, etc. Types are not first-class entities in D (there is no <code>type</code> type), but they can easily be manipulated as any other symbol, by aliasing them. So, when a template has to expose a type, it's done by aliasing it to a new name.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> allarrays;

<span class="kw">template</span> AllArraysOf(T)
{
    <span class="kw">alias</span> T    Element;
    <span class="kw">alias</span> T*   PointerTo;
    <span class="kw">alias</span> T[]  DynamicArray;
    <span class="kw">alias</span> T[<span class="dv">1</span>] StaticArray;
    <span class="kw">alias</span> T[T] AssociativeArray;
}</code></pre>
<blockquote>
<p><strong>Exposing Template Parameters.</strong> Though they are part of a template's name, its parameters are <em>not</em> directly accessible externally. Keep in mind that a template name is just a scope name. Once it's instantiated, all the <code>T</code>s and <code>U</code>s and such do not exist anymore. If you need them externally, expose them through a template member, as is done with <code>AllArraysOf.Element</code>. You will find other examples of this in section <a href="#struct-templates">Struct Templates</a> and section <a href="#class-templates">Class Templates</a>.</p>
</blockquote>
<h3 id="static-if"><code>static if</code></h3>
<h4 id="syntax-1">Syntax</h4>
<p>The <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> construct<a href="#fn2" class="footnoteRef" id="fnref2"><sup>2</sup></a> lets you decide between two code paths at compile time. It's not specific to templates (you can use it in other parts of your code), but it's incredibly useful to have your templates adapt themselves to the arguments. That way, using compile-time-calculated predicates based on the template arguments, you'll generate different code and customize the template to your need.</p>
<p>The syntax is:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span> (compileTimeExpression)
{
     <span class="co">/* Code created if compileTimeExpression is evaluated to true */</span>
}
<span class="kw">else</span> <span class="co">/* optional */</span>
{
     <span class="co">/* Code created if it&#39;s false */</span>
}</code></pre>
<p>Something really important here is a bit of compiler magic: once the code path is selected, the resulting code is instantiated in the template body, but without the curly braces. Otherwise that would create a local scope, hiding what's happening inside and would drastically limit the power of <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>. So the curly braces are there only to group the statements together.</p>
<p>If there is only one statement, you can get rid of the braces entirely, something you'll see frequently in D code. For example, suppose you need a template that 'returns' <code class="sourceCode d"><span class="kw">true</span></code> if the passed type is a dynamic array and <code class="sourceCode d"><span class="kw">false</span></code> otherwise (this kind of predicate template is developed a bit more in section [predicates]).</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> isdynamicarray;

<span class="kw">template</span> isDynamicArray(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T t == U[], U))
        <span class="kw">enum</span> isDynamicArray = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> isDynamicArray = <span class="kw">false</span>;
}</code></pre>
<p>As you can see, with no curly braces after <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> and the eponymous trick (<code>isDynamicArray</code> is a symbol defined by the template and its type is automatically deduced by the compiler), results in a very clean syntax. The <code class="sourceCode d"><span class="kw">is</span>()</code> expression part is a way to get compile-time introspection which goes hand in hand with <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>. There is a crash course on it at the end of this document (see [appendix-isExpression]).</p>
<h4 id="optional-code">Optional Code</h4>
<p>A common use of <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> is to enable or disable code: a single <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> without an <code class="sourceCode d"><span class="kw">else</span></code> clause will generate code only when the condition is true. You can find many examples of this idiom in <a href="http://dlang.org/phobos/std_range.html">std.range</a> where higher-level ranges (ranges wrapping other ranges) will activate some functionality if and only if the wrapped range can support it, like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/* We are inside a MyRange templated struct, wrapping a R. */</span>

    R innerRange;

<span class="co">/* Code that exists in all instantiations of MyRange */</span>
(...)

<span class="co">/* optional code */</span>
<span class="kw">static</span> <span class="kw">if</span> (hasLength!R) <span class="co">// does innerRange have a .length() method?</span>
    <span class="kw">auto</span> length()       <span class="co">// Then MyRange has one also.</span>
    {
        <span class="kw">return</span> innerRange.<span class="dt">length</span>;
    }

<span class="kw">static</span> <span class="kw">if</span> (isInfinite!R)     <span class="co">// Is innerRange an infinite range?</span>
    <span class="kw">enum</span> <span class="dt">bool</span> empty = <span class="kw">false</span>; <span class="co">// Then MyRange is also infinite.</span>
<span class="co">// And so on...</span></code></pre>
<h4 id="nested-static-ifs">Nested <code>static if</code>s</h4>
<p><code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>'s can be nested: just put another <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> after <code class="sourceCode d"><span class="kw">else</span></code>. Here is a template selecting an alias:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> selector;
<span class="kw">import</span> std.traits: isIntegral, isFloatingPoint;

<span class="kw">template</span> selector(T, <span class="kw">alias</span> intFoo, <span class="kw">alias</span> floatFoo, <span class="kw">alias</span> defaultFoo)
{
    <span class="kw">static</span> <span class="kw">if</span> (isIntegral!T)
       <span class="kw">alias</span> intFoo selector;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (isFloatingPoint!T)
       <span class="kw">alias</span> floatFoo selector;
    <span class="kw">else</span> <span class="co">// default case</span>
        <span class="kw">alias</span> defaultFoo selector;
}</code></pre>
<p>If you need a sort of <code>static switch</code> construct, see section [examples-staticswitch].</p>
<h4 id="recursion-with-static-if">Recursion with <code>static if</code></h4>
<h5 id="rank">Rank:</h5>
<p>Now, let's use <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> for something a bit more complicated than just dispatching between code paths: recursion. What if you know you will receive n-dimensional arrays (simple arrays, arrays of arrays, arrays of arrays of arrays, ...), and want to use the fastest, super-optimized numerical function for the 1-dim array, another one for 2D arrays and yet another one for higher-level arrays? Abstracting this away, we need a template doing some introspection on types, that will return 0 for an element (anything that's not an array), 1 for a 1-dim array (<code>T[]</code>, for some <code class="sourceCode d">T</code>), 2 for a 2-dim array (<code>T[][]</code>), and so on. Mathematicians call this the <em>rank</em> of an array, so we will use that. The definition is perfectly recursive:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> rank1;

<span class="kw">template</span> rank(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T t == U[], U))        <span class="co">// is T an array of U, for some type U?</span>
        <span class="kw">enum</span> <span class="dt">size_t</span> rank = <span class="dv">1</span> + rank!(U); <span class="co">// then let&#39;s recurse down.</span>
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">size_t</span> rank = <span class="dv">0</span>;            <span class="co">// Base case, ending the recursion.</span>
}</code></pre></td></tr></table>
<p>Lines 5 and 6 are the most interesting: with some <code class="sourceCode d"><span class="kw">is</span></code> magic, <code class="sourceCode d">U</code> has been deduced by the compiler and is accessible inside the <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> branch. We use it to peel one level of <code>[]</code> off the type and recurse downward, using <code class="sourceCode d">U</code> as a new type for instantiating <code class="sourceCode d">rank</code>. Either <code class="sourceCode d">U</code> is itself an array (in which case the recursion will continue) or it will hit the base case and stop there. Since the template defines a member named like itself, the result is directly accessible: any instantiation of <code>rank</code> will be a value of type <code class="sourceCode d"><span class="dt">size_t</span></code>.</p>
<p>Let's use it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_rank1;
<span class="kw">import</span> rank1;

<span class="kw">static</span> <span class="kw">assert</span>(rank!(<span class="dt">int</span>)       == <span class="dv">0</span>);
<span class="kw">static</span> <span class="kw">assert</span>(rank!(<span class="dt">int</span>[])     == <span class="dv">1</span>);
<span class="kw">static</span> <span class="kw">assert</span>(rank!(<span class="dt">int</span>[][])   == <span class="dv">2</span>);
<span class="kw">static</span> <span class="kw">assert</span>(rank!(<span class="dt">int</span>[][][]) == <span class="dv">3</span>);

<span class="co">/* It will work for any type, obviously */</span>
<span class="kw">struct</span> S {}

<span class="kw">static</span> <span class="kw">assert</span>(rank!(S)  == <span class="dv">0</span>);
<span class="kw">static</span> <span class="kw">assert</span>(rank!(S[])== <span class="dv">1</span>);
<span class="kw">static</span> <span class="kw">assert</span>(rank!(S*) == <span class="dv">0</span>);</code></pre>
<blockquote>
<p><strong>static assert.</strong> Putting <code class="sourceCode d"><span class="kw">static</span></code> before an <code class="sourceCode d"><span class="kw">assert</span></code> forces the <code class="sourceCode d"><span class="kw">assert</span></code> execution at compile-time. Using an <code class="sourceCode d"><span class="kw">is</span></code> expression as the test clause gives assertion on types. One common use of <code class="sourceCode d"><span class="kw">static</span> <span class="kw">assert</span></code> is to stop the compilation, for example if we ever get in a bad code path, by using <code class="sourceCode d"><span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">false</span>, someString)</code> (or <code class="sourceCode d"><span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, someString)</code>). The string is then emitted as a compiler error message.</p>
</blockquote>
<h5 id="rank-for-ranges">Rank for Ranges:</h5>
<p>D has an interesting sequence concept called a <em>range</em>. The <a href="http://dlang.org/phobos/index.html">Phobos</a> standard library comes with predefined testing templates in <a href="http://dlang.org/phobos/std_range.html">std.range</a>. Why not extend <code class="sourceCode d">rank</code> to have it deal with ranges and see if something is a range of ranges or more? A type can be tested to be a range with <code class="sourceCode d">isInputRange</code> and its element type is obtained by applying <code class="sourceCode d">ElementType</code> to the range type. Both templates are found in <a href="http://dlang.org/phobos/std_range.html">std.range</a>. Also, since arrays are included in the range concept, we can entirely ditch the array part and use only ranges. Here is a slightly modified version of <code class="sourceCode d">rank</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> rank2;
<span class="kw">import</span> std.range;

<span class="kw">template</span> rank(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (isInputRange!T)                       <span class="co">// is T a range?</span>
        <span class="kw">enum</span> <span class="dt">size_t</span> rank = <span class="dv">1</span> + rank!(ElementType!T); <span class="co">// if yes, recurse</span>
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">size_t</span> rank = <span class="dv">0</span>;                        <span class="co">// base case, stop there</span>
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> c = cycle([[<span class="dv">0</span>,<span class="dv">1</span>],[<span class="dv">2</span>,<span class="dv">3</span>]]); <span class="co">// == [[0,1],[2,3],[0,1],[2,3],[0,1]...</span>
    <span class="kw">assert</span>(rank!(<span class="dt">typeof</span>(c)) == <span class="dv">2</span>); <span class="co">// range of ranges</span>
}</code></pre>
<h5 id="base-element-type">Base Element Type:</h5>
<p>With <code class="sourceCode d">rank</code>, we now have a way to get the number of <code>[]</code>'s in an array type (<code>T[][][]</code>) or the level of nesting in a range of ranges. The complementary query would be to get the base element type, <code class="sourceCode d">T</code>, from any array of arrays ... of <code class="sourceCode d">T</code> or the equivalent for a range. Here it is:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> baseelementtype;
<span class="kw">import</span> std.range;
<span class="kw">import</span> rank2;

<span class="kw">template</span> BaseElementType(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (rank!T == <span class="dv">0</span>)      <span class="co">// not a range</span>
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, T.<span class="dt">stringof</span> ~ <span class="st">&quot; is not a range.&quot;</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (rank!T == <span class="dv">1</span>) <span class="co">// simple range</span>
        <span class="kw">alias</span> ElementType!T                     BaseElementType;
    <span class="kw">else</span>                         <span class="co">// at least range of ranges</span>
        <span class="kw">alias</span> BaseElementType!(ElementType!(T)) BaseElementType;
}</code></pre></td></tr></table>
<p>Line 8 is an example of <code>static assert</code> stopping compilation if we ever get into a bad code path. Line 12 is an example of a Matrioshka call: a template using another template's call as its parameter.</p>
<h5 id="generating-arrays">Generating Arrays:</h5>
<p>Now, what about becoming more generative by inverting the process? Given a type <code class="sourceCode d">T</code> and a rank <code class="sourceCode d">r</code> (a <code class="sourceCode d"><span class="dt">size_t</span></code>), we want to obtain <code>T[][]...[]</code>, with <code class="sourceCode d">r</code> levels of <code>[]</code>'s. A rank of 0 means producing <code class="sourceCode d">T</code> as the result type.</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> ndim;

<span class="kw">template</span> NDimArray(T, <span class="dt">size_t</span> r)
{
    <span class="kw">static</span> <span class="kw">if</span> (r == <span class="dv">0</span>)
        <span class="kw">alias</span> T NDimArray;
    <span class="kw">else</span>
        <span class="kw">alias</span> NDimArray!(T, r-<span class="dv">1</span>)[] NDimArray;
}</code></pre></td></tr></table>
<p>Here, recursion is done on line 8: we instantiate <code class="sourceCode d">NDimArray!(T,r-<span class="dv">1</span>)</code>, which is a type, then create an array of them by putting <code>[]</code> at the end and expose it through an alias. This is also a nice example of using an integral value, <code>r</code>, as a template parameter.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_ndim;
<span class="kw">import</span> ndim;

<span class="kw">alias</span> NDimArray!(<span class="dt">double</span>, <span class="dv">8</span>) Level8;
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Level8 == <span class="dt">double</span>[][][][][][][][]));
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(NDimArray!(<span class="dt">double</span>, <span class="dv">0</span>) == <span class="dt">double</span>));</code></pre>
<h5 id="repeated-composition">Repeated composition:</h5>
<p>As a last example, we will use an alias template parameter in conjunction with some <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> recursion to define a template that creates the 'exponentiation' of a function, aka its repeated composition. Here is what I mean by this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_power;
<span class="kw">import</span> repeatedcomposition;

<span class="co">// standard function</span>
<span class="dt">string</span> foo(<span class="dt">string</span> s) { <span class="kw">return</span> s ~ s;}

<span class="co">// function templates. You&#39;ll see them soon.</span>
Arr[] makeArray(Arr)(Arr array) { <span class="kw">return</span> [array,array];}

<span class="dt">void</span> main()
{
   <span class="co">// power!(foo, n) is a function.</span>
   <span class="kw">assert</span>(power!(foo, <span class="dv">0</span>)(<span class="st">&quot;a&quot;</span>) == <span class="st">&quot;a&quot;</span>);                <span class="co">// identity function</span>
   <span class="kw">assert</span>(power!(foo, <span class="dv">1</span>)(<span class="st">&quot;a&quot;</span>) == foo(<span class="st">&quot;a&quot;</span>));           <span class="co">// &quot;aa&quot;</span>
   <span class="kw">assert</span>(power!(foo, <span class="dv">2</span>)(<span class="st">&quot;a&quot;</span>) == foo(foo(<span class="st">&quot;a&quot;</span>)));      <span class="co">// &quot;aaaa&quot;</span>
   <span class="kw">assert</span>(power!(foo, <span class="dv">3</span>)(<span class="st">&quot;a&quot;</span>) == foo(foo(foo(<span class="st">&quot;a&quot;</span>)))); <span class="co">// &quot;aaaaaaaa&quot;</span>

   <span class="co">// It&#39;s even better with function templates:</span>
   <span class="kw">assert</span>(power!(makeArray, <span class="dv">0</span>)(<span class="dv">1</span>) == <span class="dv">1</span>);
   <span class="kw">assert</span>(power!(makeArray, <span class="dv">1</span>)(<span class="dv">1</span>) == [<span class="dv">1</span>,<span class="dv">1</span>]);
   <span class="kw">assert</span>(power!(makeArray, <span class="dv">2</span>)(<span class="dv">1</span>) == [[<span class="dv">1</span>,<span class="dv">1</span>],[<span class="dv">1</span>,<span class="dv">1</span>]]);
   <span class="kw">assert</span>(power!(makeArray, <span class="dv">3</span>)(<span class="dv">1</span>) == [[[<span class="dv">1</span>,<span class="dv">1</span>],[<span class="dv">1</span>,<span class="dv">1</span>]],[[<span class="dv">1</span>,<span class="dv">1</span>],[<span class="dv">1</span>,<span class="dv">1</span>]]]);
}</code></pre>
<p>First, this is a template that 'returns' (becomes, rather) a function. It's easy to do with the eponymous trick: just define inside the template a function with the same name. Secondly, it's clearly recursive in its definition, with two base cases: if the exponent is zero, then we shall produce the identity function and if the exponent is one, we shall just return the input function itself. That being said, <code class="sourceCode d">power</code> writes itself:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> repeatedcomposition;

<span class="kw">template</span> power(<span class="kw">alias</span> fun, <span class="dt">uint</span> exponent)
{
    <span class="kw">static</span> <span class="kw">if</span> (exponent == <span class="dv">0</span>) <span class="co">// degenerate case -&gt; id function</span>
        <span class="kw">auto</span> power(Args)(Args args) { <span class="kw">return</span> args; }
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (exponent == <span class="dv">1</span>) <span class="co">// end-of-recursion case -&gt; fun</span>
        <span class="kw">alias</span> fun power;
    <span class="kw">else</span>
        <span class="kw">auto</span> power(Args...)(Args args)
        {
            <span class="kw">return</span> .power!(fun, exponent-<span class="dv">1</span>)(fun(args));
        }
}</code></pre></td></tr></table>
<blockquote>
<p><strong>.power</strong> If you are wondering what's with the <code>.power</code> syntax on line 12, it's because by defining an eponymous template, we hide the parent template's name. So inside <code>power(Args...)</code>, <code>power</code> refers to <code>power(Args...)</code> and not <code class="sourceCode d">power(<span class="kw">alias</span> fun, <span class="dt">uint</span> exponent)</code>. Here we want a new <code class="sourceCode d">power</code> to be generated so we call on the global <code class="sourceCode d">power</code> template with the 'global scope' operator (<code>.</code>).</p>
</blockquote>
<p>In all three branches of <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>, <code class="sourceCode d">power</code> exposes a <code class="sourceCode d">power</code> member, activating the eponymous template trick and allowing for an easy use by the client. Note that this template will work not only for unary (one argument) functions but also for n-args functions <a href="#fn3" class="footnoteRef" id="fnref3"><sup>3</sup></a>, for delegates and for structs or classes that define the <code>()</code>(ie, <code class="sourceCode d">opCall</code>) operator and for function templates... <a href="#fn4" class="footnoteRef" id="fnref4"><sup>4</sup></a></p>
<p>Now, are you beginning to see the power of templates?</p>
<blockquote>
<p><strong>Curried Templates?</strong> No, I do not mean making them spicy, but separating the template's arguments, so as to call them in different places in your code. For <code class="sourceCode d">power</code>, that could mean doing <code class="sourceCode d"><span class="kw">alias</span> power!<span class="dv">2</span> square;</code> somewhere and then using <code>square!fun1</code>, <code>square!fun2</code> at your leisure: the <code class="sourceCode d">exponent</code> parameter and the <code class="sourceCode d">fun</code> alias are separated. In fact, <code class="sourceCode d">power</code> is already partially curried: <code class="sourceCode d">fun</code> and <code class="sourceCode d">exponent</code> are separated from <code class="sourceCode d">Args</code>. For more on this, see section <a href="#templates-in-templates">Templates In Templates</a>. Given a template <code class="sourceCode d">temp</code>, writing a <code class="sourceCode d">curry</code> template that automatically generates the code for a curried version of <code class="sourceCode d">temp</code> is <em>also</em> possible, but outside the scope of this document.</p>
</blockquote>
<h4 id="templates-specializations">Templates Specializations</h4>
<p>Up to now, when we write a <code class="sourceCode d">T</code> in a template parameter list, there is no constraint on the type that <code class="sourceCode d">T</code> can become during instantiation. Template specialization is a small 'subsyntax', restricting templates instantiations to a subset of all possible types and directing the compiler into instantiating a particular version of a template instead of another. If you've read [appendix-isexpression] on the <code class="sourceCode d"><span class="kw">is</span>()</code> expression, you already know how to write them. If you didn't, please do it now, as it's really the same syntax. These specializations are a direct inheritance from C++ templates, up to the way they are written and they existed in D from the very beginning, long before <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> or templates constraints were added.</p>
<p>The specializations are added in the template parameter list, the <code>(T, U, V)</code> part of the template definition. <code>Type : OtherType</code> restricts <code class="sourceCode d">Type</code> to be implicitly convertible into <code>OtherType</code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> specialization1;

<span class="kw">template</span> ElementType(T : U[], U) <span class="co">// can only be instantiated with arrays</span>
{
    <span class="kw">alias</span> U ElementType;
}

<span class="kw">template</span> ElementType(T : U[n], U, <span class="dt">size_t</span> n) <span class="co">// only with static arrays</span>
{
    <span class="kw">alias</span> U ElementType;
}

<span class="kw">class</span> Array { <span class="kw">alias</span> <span class="dt">int</span> ElementType;}

<span class="kw">template</span> ElementType(T : Array)
{
    <span class="kw">alias</span> Array.ElementType ElementType;
}</code></pre>
<p>Now, the idea may seem strange to you: if you know you want to restrict <code class="sourceCode d">Type</code> to be <code class="sourceCode d">AnotherType</code>, why make it a template parameter? It's because of templates specializations' main use: you can write different implementations of a template (with the same name, obviously), and when asked to instantiate one of them, the compiler will automatically decide which one to use, taking the 'most adapted' to the provided arguments. 'Most adapted' obeys some complicated rules you can find on the D Programming Language website, but they act in a natural way most of the time. The neat thing is that you can define the most general template <em>and</em> some specialization. The specialized ones will be chosen when it's possible.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> specialization2;

<span class="kw">template</span> InnerType(T : U*, U) <span class="co">// Specialization for pointers</span>
{
    <span class="kw">alias</span> U InnerType;
}

<span class="kw">template</span> InnerType(T : U[], U) <span class="co">// Specialization for dyn. arrays</span>
{ <span class="co">/*...*/</span> }

<span class="kw">template</span> InnerType(T) <span class="co">// Standard, default case</span>
{ <span class="co">/*...*/</span> }

<span class="dt">void</span> main()
{
    <span class="dt">int</span>* p;
    <span class="dt">int</span> i;
    <span class="kw">alias</span> InnerType!(<span class="dt">typeof</span>(p)) Pointer; <span class="co">// pointer spec. selected</span>
    <span class="kw">alias</span> InnerType!(<span class="dt">typeof</span>(i)) Default; <span class="co">// standard template selected</span>
}</code></pre>
<p>This idiom is frequently used in C++, where there is no (built-in) <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> construct or template constraints. Oldish D templates used it a lot, too, but since other ways have been around for some years, recent D code seems to be more constraint-oriented: have a look at heavily templated Phobos modules, for example <a href="http://dlang.org/phobos/std_algorithm.html">std.algorithm</a> or <a href="http://dlang.org/phobos/std_range.html">std.range</a>.</p>
<blockquote>
<p><strong>Specializations or static if or Templates Constraints?</strong> Yes indeed. Let's defer this discussion for when we have seen all three subsystems.</p>
</blockquote>
<h3 id="default-values">Default Values</h3>
<p>Like functions parameters, templates parameters can have default values. The syntax is the same: <code>Param = defaultValue</code>. The default can be anything that makes sense with respect to the parameter kind: a type, a literal value, a symbol or another template parameter.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> def;

<span class="kw">template</span> Default(T = <span class="dt">int</span>, <span class="dt">bool</span> flag = <span class="kw">false</span>)
{
    <span class="kw">static</span> <span class="kw">if</span> (flag)
        <span class="kw">alias</span> T Default;
    <span class="kw">else</span>
        <span class="kw">alias</span> <span class="dt">void</span> Default;
}

<span class="kw">alias</span> Default!(<span class="dt">double</span>) D1;       <span class="co">// Instantiate Default!(double, false)</span>
<span class="kw">alias</span> Default!(<span class="dt">double</span>, <span class="kw">true</span>) D2; <span class="co">// Instantiate Default!(double, true) (Doh!)</span>
<span class="kw">alias</span> Default!() D3;             <span class="co">// Instantiate Default!(int, false)</span></code></pre>
<p>In contrast to function parameters, thanks to <a href="#templates-specializations">Templates Specializations</a> or <a href="#ifti">IFTI</a>, some template parameters can be automatically deduced by the compiler. So, default template parameters are not required to be the final parameters in the list:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> deduced;
<span class="kw">import</span> std.typecons: Tuple;

<span class="kw">template</span> Deduced(T : U[], V = T, U)
{
    <span class="kw">alias</span> Tuple!(T,U,V) Deduced;
}

<span class="kw">alias</span> Deduced!(<span class="dt">int</span>[], <span class="dt">double</span>) D1; <span class="co">// U deduced to be int. Force V to be a double.</span>
<span class="kw">alias</span> Deduced!(<span class="dt">int</span>[]) D2; <span class="co">// U deduced to be int. V is int, too.</span></code></pre>
<blockquote>
<p><strong>Specialization and Default Value?</strong> Yes you can. Put the specialization first, then the default value. Like this: <code>(T : U[] = int[], U)</code>. It's not commonly used, though.</p>
</blockquote>
<p>As for functions, well-chosen defaults can greatly simplify standard calls. See for example <a href="http://dlang.org/phobos/std_algorithm.html#sort">std.algorithm.sort</a>. It's parameterized on a predicate and a swapping strategy, but both are adapted to what most people need when sorting. That way, most client uses of the template will be short and clean, but customization to their own need is still possible.</p>
<blockquote>
<p><strong>TODO</strong> Maybe something on template dummy parameters, like those used by <a href="http://dlang.org/phobos/std_traits.html#ReturnType">std.traits.ReturnType</a>. Things like <code class="sourceCode d">dummy == <span class="dt">void</span></code>.</p>
</blockquote>
<h2 id="function-templates">Function Templates</h2>
<h3 id="syntax-2">Syntax</h3>
<p>If you come from languages with generics, maybe you thought D templates were all about parameterized classes and functions and didn't see any interest in the previous sections (acting on types?). Fear not, you can also do type-generic functions and such in D, with the added generative power of templates.</p>
<p>As we have seen in <a href="#the-eponymous-trick">The Eponymous Trick</a>, if you define a function inside a template and use the template's own name, you can call it easily:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> function_declaration1;
<span class="kw">import</span> std.conv : to;

<span class="co">// declaration:</span>
<span class="kw">template</span> myFunc(T, <span class="dt">int</span> n)
{
    <span class="kw">auto</span> myFunc(T t) { <span class="kw">return</span> to!<span class="dt">int</span>(t) * n;}
}

<span class="dt">void</span> main()
{
    <span class="co">// call:</span>
    <span class="kw">auto</span> result = myFunc!(<span class="dt">double</span>,<span class="dv">3</span>)(<span class="fl">3.1415</span>);

    <span class="kw">assert</span>(result == to!<span class="dt">int</span>(<span class="fl">3.1415</span>)*<span class="dv">3</span>);
}</code></pre>
<p>Well, the full story is even better. First, D has a simple way to declare a function template: just put a template parameter list before the argument list:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> function_declaration2;
<span class="kw">import</span> std.conv:to;

<span class="dt">string</span> concatenate(A,B)(A a, B b)
{
    <span class="kw">return</span> to!<span class="dt">string</span>(a) ~ to!<span class="dt">string</span>(b);
}

Arg select(<span class="dt">string</span> how = <span class="st">&quot;max&quot;</span>, Arg)(Arg arg0, Arg arg1)
{
    <span class="kw">static</span> <span class="kw">if</span> (how == <span class="st">&quot;max&quot;</span>)
        <span class="kw">return</span> (arg0 &lt; arg1) ? arg1 : arg0;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (how == <span class="st">&quot;min&quot;</span>)
        <span class="kw">return</span> (arg0 &lt; arg1) ? arg0 : arg1;
    <span class="kw">else</span>
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>,
        <span class="st">&quot;select: string &#39;how&#39; must be either \&quot;max\&quot; or \&quot;min\&quot;.&quot;</span>);
}</code></pre>
<p>Nice and clean, uh? Notice how the return type can be templated too, using <code class="sourceCode d">Arg</code> as a return type in <code class="sourceCode d">select</code>.</p>
<h3 id="auto-return">auto return</h3>
<p>Since you can select among code paths, the function return type can vary widely, depending on the template parameters you passed it. Use <code class="sourceCode d"><span class="kw">auto</span></code> to simplify your code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> morph;

<span class="co">// What morph will return will heavily depend on T and U</span>
<span class="kw">auto</span> morph(<span class="kw">alias</span> f, T, U)(U arg)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">class</span>))
        <span class="kw">return</span> <span class="kw">new</span> T(f(arg));
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">struct</span>))
        <span class="kw">return</span> T(f(arg));
    <span class="kw">else</span>
        <span class="kw">return</span>; <span class="co">// void-returning function.</span>
}</code></pre>
<blockquote>
<p><strong>auto ref.</strong> A function template can have an <code>auto ref</code> return type. That means that for templates where the returned values are lvalues, the template will get the <code class="sourceCode d"><span class="kw">ref</span></code>ed version. And the non-<code class="sourceCode d"><span class="kw">ref</span></code> version if not. I should add some examples for that behaviour.</p>
</blockquote>
<h3 id="ifti">IFTI</h3>
<p>Even better is Implicit Function Template Instantiation (IFTI), which means that the compiler will generally be able to automatically determine a template's parameters by studying the function arguments. If some template arguments are pure compile-time parameters, just provide them directly:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> ifti;
<span class="kw">import</span> function_declaration2;

<span class="kw">struct</span> Foo {}

<span class="dt">void</span> main()
{
    <span class="dt">string</span> res1 = concatenate(<span class="dv">1</span>, <span class="fl">3.14</span>); <span class="co">// A is int and B is double</span>
    <span class="dt">string</span> res2 = concatenate(<span class="st">&quot;abc&quot;</span>, Foo()); <span class="co">// A is string, B is Foo</span>

    <span class="kw">auto</span> res3 = select(<span class="dv">3</span>,<span class="dv">4</span>); <span class="co">// how is &quot;max&quot;, Arg is int.</span>
    <span class="kw">auto</span> res4 = select!<span class="st">&quot;min&quot;</span>(<span class="fl">3.1416</span>, <span class="fl">2.718</span>); <span class="co">// how is &quot;min&quot;, Arg is double.</span>
}</code></pre>
<p>As you can see, this results in very simple calling code. So we can both declare function templates and call them with a very clean syntax. The same can be done with structs or classes and such, as you will see in the next sections. In fact, the syntax is so clean that, if you are like me, you may forget from time to time that you are <em>not</em> manipulating a function (or a struct, etc.): you are manipulating a template, a parameterized piece of code.</p>
<blockquote>
<p><strong>A Mantra.</strong> <code class="sourceCode d">XXX</code> templates are not <code class="sourceCode d">XXX</code>s, they are templates. With <code class="sourceCode d">XXX</code> being any of (function, struct, class, interface, union). Templates are parameterized scopes and scopes are not first-class in D: they have no type, they cannot be assigned to a variable, they cannot be returned from functions. That means, for example, that you <em>cannot</em> return function templates, you cannot inherit from class templates and so on. Of course, <em>instantiated</em> templates are perfect examples of functions, classes, and such. Those you can inherit, return...</p>
</blockquote>
<p>We may encounter <strong>The Mantra</strong> again in this tutorial.</p>
<h3 id="example-flattening-arrays-and-ranges">Example: Flattening Arrays and Ranges</h3>
<p>Let's use what we have just seen in a concrete way. In D, you can manipulate 2D and 3D arrays, but sometimes need to process them linearly. As of this writing, neither <a href="http://dlang.org/phobos/std_algorithm.html">std.algorithm</a> nor <a href="http://dlang.org/phobos/std_range.html">std.range</a> provide a <code class="sourceCode d">flatten</code> function. Beginning with simple arrays, here is what we want:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_flatten1;
<span class="kw">import</span> flatten1;

<span class="dt">void</span> main()
{
    <span class="kw">assert</span>( flatten([[<span class="dv">0</span>,<span class="dv">1</span>],[<span class="dv">2</span>,<span class="dv">3</span>],[<span class="dv">4</span>]]) == [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>] );
    <span class="kw">assert</span>( flatten([[<span class="dv">0</span>,<span class="dv">1</span>]]) == [<span class="dv">0</span>,<span class="dv">1</span>] );
    <span class="kw">assert</span>( flatten([<span class="dv">0</span>,<span class="dv">1</span>]) == [<span class="dv">0</span>,<span class="dv">1</span>] );
    <span class="kw">assert</span>( flatten(<span class="dv">0</span>) == <span class="dv">0</span> );

    <span class="kw">assert</span>( flatten([[[<span class="dv">0</span>,<span class="dv">1</span>],[]], [[<span class="dv">2</span>]], [[<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>]], [[]], [[<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>]]])
            == [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>,<span class="dv">5</span>,<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>] );
}</code></pre>
<p>So, studying the examples, we want a simple array (rank == 1) or a non-array (rank == 0) to be unaffected by <code class="sourceCode d">flatten</code>: it just returns them. For arrays of rank 2 or higher, it collapses the elements down to a rank-1 array. It's classically recursive: we will apply <code class="sourceCode d">flatten</code> on all sub-arrays with <a href="http://dlang.org/phobos/std_algorithm.html#map">std.algorithm.map</a> and concatenate the elements with <a href="http://dlang.org/phobos/std_algorithm.html#reduce">std.algorithm.reduce</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> flatten1;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> rank2;

<span class="kw">auto</span> flatten(Arr)(Arr array)
{
    <span class="kw">static</span> <span class="kw">if</span> (rank!Arr &lt;= <span class="dv">1</span>)
        <span class="kw">return</span> array;
    <span class="kw">else</span>
    {
        <span class="kw">auto</span> children = map!(.flatten)(array);
        <span class="kw">return</span> reduce!<span class="st">&quot;a~b&quot;</span>(children); <span class="co">// concatenate the children</span>
    }
}</code></pre>
<p>We make good use of D <code class="sourceCode d"><span class="kw">auto</span></code> return parameter for functions there. In fact, a single call to <code class="sourceCode d">flatten</code> will create one instance per level, all with a different return type.</p>
<p>Note that <code class="sourceCode d">flatten</code> works perfectly on ranges too, but is not lazy: it eagerly concatenates all the elements down to the very last one in the innermost range. Ranges being lazy, a good <code class="sourceCode d">flatten</code> implementation for them should itself be a range that delivers the elements one by one, calculating the next one only when asked to (and thus, would work on infinite or very long ranges too, which the previous simple implementation cannot do). Implementing this means creating a <a href="#struct-templates">struct template</a> with a <a href="#factory-functions">factory function</a>. You will find this as an example <a href="#example-a-concat-flatten-range">here</a>.</p>
<p>From our current <code class="sourceCode d">flatten</code>, it's an interesting exercise to add another parameter: the number of levels you want to flatten. Only the first three levels or last two innermost, for example. Just add an integral template parameter that gets incremented (or decremented) when you recurse and is another stopping case for the recursion. Positive levels could mean the outermost levels, while a negative argument would act on the innermost ones. A possible use would look like this:</p>
<pre class="sourceCode d"><code class="sourceCode d">flatten!<span class="dv">1</span>([[[<span class="dv">0</span>,<span class="dv">1</span>],[]], [[<span class="dv">2</span>]], [[<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>]], [[]], [[<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>]]]);
     <span class="co">// == [[[0,1],[],[2],[3], [4,5],[],[6,7,8]]</span>
flatten!<span class="dv">2</span>([[[<span class="dv">0</span>,<span class="dv">1</span>],[]], [[<span class="dv">2</span>]], [[<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>]], [[]], [[<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>]]]);
     <span class="co">// == [0,1,2,3,4,5,6,7,8]</span>
flatten!<span class="dv">0</span>([[[<span class="dv">0</span>,<span class="dv">1</span>],[]], [[<span class="dv">2</span>]], [[<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>]], [[]], [[<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>]]]);
     <span class="co">// ==[[[0,1],[]], [[2]], [[3], [4,5]], [[]], [[6,7,8]]]</span>
flatten!(-<span class="dv">1</span>)([[[<span class="dv">0</span>,<span class="dv">1</span>],[]], [[<span class="dv">2</span>]], [[<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>]], [[]], [[<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>]]]);
     <span class="co">// ==[[[0,1]], [[2]], [[3,4,5]], [[]], [[6,7,8]]]</span></code></pre>
<h3 id="anonymous-function-templates">Anonymous Function Templates</h3>
<p>In D, you can define anonymous functions (delegates even, that is: closures):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> anonymous_function1;

<span class="kw">auto</span> adder(<span class="dt">int</span> a)
{
    <span class="kw">return</span> (<span class="dt">int</span> b) { <span class="kw">return</span> a+b;};
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> add1 = adder(<span class="dv">1</span>); <span class="co">// add1 is an int delegate(int)</span>
    <span class="kw">assert</span>(add1(<span class="dv">2</span>) == <span class="dv">3</span>);
}</code></pre>
<p>In the previous code, <code class="sourceCode d">adder</code> returns an anonymous delegate. Could <code class="sourceCode d">adder</code> be templated? Ha! Remember <strong>The Mantra</strong>: function templates are templates and cannot be returned. For this particular problem, there are two possible solutions. Either you do not need any new type and just use <code class="sourceCode d">T</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> anonymous_function2;

<span class="kw">auto</span> adder(T)(T a)
{
    <span class="kw">return</span> (T b) { <span class="kw">return</span> a+b;};
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> add1f = adder(<span class="fl">1.0</span>); <span class="co">// add1f is an float delegate(float)</span>
    <span class="kw">assert</span>(add1f(<span class="fl">2.0</span>) == <span class="fl">3.0</span>);

    <span class="kw">import</span> std.bigint;

    <span class="co">// addBigOne accepts a BigInt and returns a BigInt</span>
    <span class="kw">auto</span> addBigOne = adder(BigInt(<span class="st">&quot;1000000000000000&quot;</span>));
    <span class="kw">assert</span>(addBigOne(BigInt(<span class="st">&quot;1&quot;</span>)) == BigInt(<span class="st">&quot;1000000000000001&quot;</span>));

    <span class="co">// But:</span>
    <span class="co">// auto error = add1(3.14); // Error! Waiting for an int, getting a double.</span>
}</code></pre>
<p>In the previous example, the returned anonymous delegate is <em>not</em> templated. It just happens to use <code class="sourceCode d">T</code>, which is perfectly defined once instantiation is done. If you really need to return something that can be called with any type, use an inner struct (see the section on <a href="#inner-structs">inner structs</a>).</p>
<p>Now, it may come as a surprise to you that D <em>does</em> have anonymous function templates. The syntax is a purified version of anonymous functions:</p>
<pre class="sourceCode d"><code class="sourceCode d">(a,b) { <span class="kw">return</span> a+b;}</code></pre>
<p>Yes, the previous skeleton of a function is an anonymous template. But, remember The Mantra: you cannot return them. And due to (to my eyes) a bug in <code class="sourceCode d"><span class="kw">alias</span></code> grammar, you cannot alias them to a symbol:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">alias</span> (a){ <span class="kw">return</span> a;} Id; <span class="co">// Error</span></code></pre>
<p>So what good are they? You can use them with template alias parameters, when these stand for functions and function templates:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> calltwice;

<span class="kw">template</span> callTwice(<span class="kw">alias</span> fun)
{
    <span class="kw">auto</span> callTwice(T)(T t)
    {
        <span class="kw">return</span> fun(fun(t));
    }
}

<span class="kw">unittest</span>
{
    <span class="kw">alias</span> callTwice!( (a){ <span class="kw">return</span> a+<span class="dv">1</span>;}) addTwo;
    <span class="kw">assert</span>(addTwo(<span class="dv">2</span>) == <span class="dv">4</span>);
}</code></pre>
<p>Since they are delegates, they can capture local symbols:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_calltwice;
<span class="kw">import</span> calltwice;

<span class="kw">unittest</span>
{
    <span class="kw">enum</span> b = <span class="dv">3</span>; <span class="co">// Manifest constant, initialized to 3</span>
    <span class="kw">alias</span> callTwice!( (a){ <span class="kw">return</span> a+b;}) addTwoB;
    <span class="kw">assert</span>(addTwoB(<span class="dv">2</span>) == <span class="dv">2</span> + <span class="dv">3</span> + <span class="dv">3</span>);
}</code></pre>
<blockquote>
<p><strong>TODO.</strong> Some paragraphs on the new <code class="sourceCode d">(a,b) =&gt; a+b</code> syntax.</p>
</blockquote>
<h3 id="closures-are-a-poor-mans-objects">Closures are a Poor Man's Objects</h3>
<p>D closures can wrap runtime environment and keep them near their hot little hearts. We can of course create them with a template. To obtain the equivalent of an object, let's create a function that returns a tuple (a <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> with named arguments.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> makecounter;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.typecons;

<span class="kw">auto</span> makeCounter(T)(T _counter = T.<span class="dt">init</span>) <span class="kw">if</span> (isNumeric!T)
{
    <span class="dt">bool</span> sense = <span class="kw">true</span>;
    <span class="kw">auto</span> changeSense = () { sense = !sense;};
    <span class="kw">auto</span> inc = (T increment)
               { _counter += (sense ? increment : -increment); };
    <span class="kw">auto</span> dec = (T decrement)
               { _counter += (sense ? -decrement : decrement); };
    <span class="kw">auto</span> counter = (){ <span class="kw">return</span> _counter;};

    <span class="kw">return</span> Tuple!( <span class="dt">typeof</span>(changeSense), <span class="st">&quot;changeSense&quot;</span>
                 , <span class="dt">typeof</span>(inc), <span class="st">&quot;inc&quot;</span>
                 , <span class="dt">typeof</span>(dec), <span class="st">&quot;dec&quot;</span>
                 , <span class="dt">typeof</span>(counter), <span class="st">&quot;counter&quot;</span>)
                 (changeSense, inc, dec, counter);
}</code></pre>
<p>The <code class="sourceCode d"><span class="kw">if</span></code> part after the argument list is just sanity-check template constraint (they are described in <a href="#constraints">the section on constraints</a>). The returned <code class="sourceCode d">Tuple</code> is a bit heavy for my taste, but using named tuple fields gives us a nice object-like call syntax.<a href="#fn5" class="footnoteRef" id="fnref5"><sup>5</sup></a> Otherwise, a simple <code class="sourceCode d"><span class="kw">return</span> tuple(changeSense, inc, dec, counter);</code> could have been used but then the inner closures would have to be accessed by their index and not a name.</p>
<p>Here is how to use it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_makecounter;
<span class="kw">import</span> makecounter;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> c = makeCounter(<span class="dv">0</span>); <span class="co">// T is int.</span>
    <span class="kw">auto</span> c2 = makeCounter!<span class="dt">int</span>; <span class="co">// The very same.</span>

    c.inc(<span class="dv">5</span>);
    <span class="kw">assert</span>(c.counter() == <span class="dv">5</span>);
    c.inc(<span class="dv">10</span>);
    <span class="kw">assert</span>(c.counter() == <span class="dv">15</span>);
    c.changeSense(); <span class="co">// now each increment will in fact decrement</span>
    c.inc(<span class="dv">5</span>);
    <span class="kw">assert</span>(c.counter() == <span class="dv">10</span>);
}</code></pre>
<h3 id="function-overloading">Function Overloading</h3>
<blockquote>
<p><strong>Unfinished</strong> OK, I need to write something on this.</p>
</blockquote>
<h3 id="storage-classes">Storage Classes</h3>
<p>As seen in section <a href="#instantiating-a-template">Instantiating</a>, storage classes get applied to types during instantiation. It also works for function templates arguments:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> storage;

<span class="dt">void</span> init(T)(<span class="kw">ref</span> T t)
{
    t = T.<span class="dt">init</span>;
}

<span class="kw">unittest</span>
{
    <span class="dt">int</span> i = <span class="dv">10</span>;
    init(i);
    <span class="kw">assert</span>(i == <span class="dv">0</span>);
}</code></pre>
<p>Should the need arise, this means you can customize your storage classes according to template arguments. There is no built-in syntax for that, so you'll have to resort to our good friend <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> and the eponymous trick:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// Has anyone a better example?</span>
<span class="kw">module</span> init;

<span class="kw">template</span> init(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">immutable</span>) || <span class="kw">is</span>(T == <span class="kw">const</span>))
        <span class="dt">void</span> init(T t) {} <span class="co">// do nothing</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">class</span>))
        <span class="dt">void</span> init(<span class="kw">ref</span> T t)
        {
            t = <span class="kw">new</span> T();
        }
    <span class="kw">else</span>
        <span class="dt">void</span> init(<span class="kw">ref</span> T t)
        {
            t = T.<span class="dt">init</span>;
        }
}</code></pre>
<h3 id="properties-are-automatically-deduced">Properties are Automatically Deduced</h3>
<p>In D, a function can have the following properties:</p>
<ul>
<li>A function can be tagged with the <code class="sourceCode d"><span class="kw">pure</span></code> property, which means it does not have side-effects: the value you get back is the only thing that matters.</li>
<li>They can also be tagged with <code class="sourceCode d">@safe</code>, <code class="sourceCode d">@trusted</code> and <code class="sourceCode d">@system</code>. <code class="sourceCode d">@safe</code> means a function cannot corrupt memory. A <code class="sourceCode d">@trusted</code> function can call <code class="sourceCode d">@safe</code> ones, but offers no other guaranty concerning memory. And a <code class="sourceCode d">@system</code> function may do whatever it wants.</li>
<li>The last property is <code class="sourceCode d"><span class="kw">nothrow</span></code> which means the function will not throw any exceptions.</li>
</ul>
<p>As the compiler gets complete access to a function template code, it can analyze it and automatically deduce properties for you. This feature is still quite new as of this writing, but it seems to work. So, <em>all</em> of your function templates will get a smattering of properties when they are instantiated (these properties will of course vary with the template parameters).</p>
<h3 id="in-and-out-clauses">in and out Clauses</h3>
<p>The <code class="sourceCode d"><span class="kw">in</span></code> and <code class="sourceCode d"><span class="kw">out</span></code> clauses for a function are given full access to a template's parameters. As for other parameterized code, that means you can use <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> to enable or disable code, depending on the template arguments.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> inoutclauses;
<span class="kw">import</span> std.complex, std.math, std.traits;

<span class="kw">auto</span> squareRoot(N)(N n) <span class="kw">if</span> (isNumeric!N || isComplex!N)
<span class="kw">in</span>
{
    <span class="co">// no need to do that for a complex.</span>
    <span class="kw">static</span> <span class="kw">if</span> (isNumeric!N)
        <span class="kw">assert</span>(n &gt; <span class="dv">0</span>);
}
<span class="kw">body</span>
{
    <span class="kw">return</span> sqrt(n);
}</code></pre>
<h3 id="modifying-functions">Modifying Functions</h3>
<p>This section will show you how to use wrapper templates to add new functionalities to pre-defined functions. More powerful examples are shown in , but they use templates we have not seen yet. Be sure to have a look at them when you can, though.</p>
<blockquote>
<p><strong>Unfinished!</strong> I want to put some small function-wrapping templates:</p>
</blockquote>
<ul>
<li>making a function accept tuples</li>
<li>making a function have named parameters (sort of)</li>
<li>making a function have default values for its args</li>
<li>making a function accept more args than the original</li>
<li>making a function accept arguments of a different type (that's useful when mapping on tuples, like in section [Tuples As Sequences])</li>
</ul>
<h4 id="accepting-a-tuple">Accepting a Tuple</h4>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> acceptingtuple;

<span class="kw">template</span> tuplify(<span class="kw">alias</span> fun)
{
    <span class="kw">auto</span> tuplify(T...)(Tuple!T tup)
    {
        <span class="kw">return</span> fun(tup.expand);
    }
}</code></pre>
<p>Another interesting (and much more complicated) example is <code class="sourceCode d">juxtapose</code> (see section [juxtapose]).</p>
<h4 id="mapping-n-ranges-in-parallel">Mapping n ranges in parallel</h4>
<blockquote>
<p><strong>TODO</strong> Some explanation. Showing the interest of mapping n ranges in parallel.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nmap;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.typetuple: allSatisfy;
<span class="kw">import</span> acceptingtuple;

<span class="co">// Very easy to do, now:</span>
<span class="kw">auto</span> nmap(<span class="kw">alias</span> fun, R...)(R ranges) <span class="kw">if</span> (allSatisfy!(isInputRange,R))
{
    <span class="kw">return</span> map!(tuplify!fun)(zip(ranges));
}</code></pre>
<p>More complicated: <a href="http://dlang.org/phobos/std_algorithm.html#map">std.algorithm.map</a> accepts more than one function as template arguments. In that case, the functions are all mapped in parallel on the range, internally using <a href="http://dlang.org/phobos/std_functional.html#adjoin">std.functional.adjoin</a>. Here we can extend <code class="sourceCode d">nmap</code> to accept <span class="math"><em>n</em></span> functions in parallel too. There is a first difficulty:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> nmap(fun..., R...)(R ranges) <span class="kw">if</span> (allSatisfy!(isInputRange, R))
{ ... }   ^^^^^^^^^^^^ Uh?</code></pre>
<p>See the problem? We need both a variable list of functions and a variable list of ranges. But template parameters tuples must be the last parameter of a template: there can be only one. <a href="#templates-in-templates">Double-stage templates</a> come to the rescue:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> nmap(fun...) <span class="kw">if</span> (fun.<span class="dt">length</span> &gt;= <span class="dv">1</span>)
{
    <span class="kw">auto</span> nmap(R...)(R ranges) <span class="kw">if</span> (allSatisfy!(isInputRange, R))
    {...}
}</code></pre>
<p>Now the two parts are well separated. Which gives us the final code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nmap2;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.functional : adjoin;
<span class="kw">import</span> std.range;
<span class="kw">import</span> std.typetuple : allSatisfy;
<span class="kw">import</span> acceptingtuple; <span class="co">// tuplify</span>

<span class="kw">template</span> nmap(fun...) <span class="kw">if</span> (fun.<span class="dt">length</span> &gt;= <span class="dv">1</span>)
{
    <span class="kw">auto</span> nmap(R...)(R ranges) <span class="kw">if</span> (allSatisfy!(isInputRange, R))
    {
        <span class="kw">alias</span> adjoin!(staticMap!(tuplify, fun)) _fun;
        <span class="kw">return</span> map!(_fun)(zip(ranges));
    }
}</code></pre>
<blockquote>
<p><strong>TODO.</strong> Give an example with <code class="sourceCode d">max</code>, it works!</p>
</blockquote>
<p>And here is the <span class="math"><em>n</em></span>-ranges version of <a href="http://dlang.org/phobos/std_algorithm.html#filter">std.algorithm.filter</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nfilter;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.range;
<span class="kw">import</span> std.typetuple : allSatisfy;

<span class="kw">import</span> acceptingtuple; <span class="co">// tuplify</span>

<span class="kw">auto</span> nfilter(<span class="kw">alias</span> fun, R...)(R ranges) <span class="kw">if</span> (allSatisfy!(isInputRange, R))
{
    <span class="kw">return</span> filter!(tuplify!fun)(zip(ranges));
}</code></pre>
<blockquote>
<p><strong>TODO.</strong> Examples, lots of examples.</p>
</blockquote>
<h2 id="struct-templates">Struct Templates</h2>
<h3 id="syntax-3">Syntax</h3>
<p>As you might have guessed, declaring a struct template is done just by putting a list of template parameters after the struct name, like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tree1;
<span class="kw">import</span> std.array;

<span class="kw">struct</span> Tree(T)
{
    T value;
    Tree[] children;

    <span class="dt">bool</span> isLeaf() @property { <span class="kw">return</span> children.empty;}
    <span class="co">/* More tree functions: adding children, removing some,... */</span>
}</code></pre>
<blockquote>
<p><strong>Tree[] or Tree!(T)[]?</strong> Remember that inside a template declaration, the template's name refers to the current instantiation. So inside <code>Tree(T)</code>, the name <code class="sourceCode d">Tree</code> refers to a <code>Tree!T</code>.</p>
</blockquote>
<p>This gives us a run-of-the-mill generic tree, which is created like any other template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_tree;
<span class="kw">import</span> tree1;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> t0 = Tree!<span class="dt">int</span>(<span class="dv">0</span>);
    <span class="kw">auto</span> t1 = Tree!<span class="dt">int</span>(<span class="dv">1</span>, [t0,t0]);
    Tree!<span class="dt">int</span>[] children = t1.children;
}</code></pre>
<p>As with all previous templates, you can parametrize your structs using much more than simple types:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> heap1;

<span class="dt">bool</span> lessThan(T)(T a, T b) { <span class="kw">return</span> a&lt;b;}

<span class="kw">struct</span> Heap(Type, <span class="kw">alias</span> predicate = lessThan, <span class="dt">float</span> reshuffle = <span class="fl">0.5f</span>)
{
    <span class="co">// predicate governs the internal comparison</span>
    <span class="co">// reshuffle deals with internal re-organizing of the heap</span>
    Type[] values;
<span class="co">/*...*/</span>
}</code></pre>
<p>Struct templates are heavily used in <a href="http://dlang.org/phobos/std_algorithm.html">std.algorithm</a> and <a href="http://dlang.org/phobos/std_range.html">std.range</a> for lazy evaluation, have a look there.</p>
<h3 id="factory-functions">Factory Functions</h3>
<p>Now, there is one limitation: struct constructors do not do activate <a href="#ifti">IFTI</a> like template functions do. In the previous subsection to instantiate <code>Tree(T)</code>, I had to explicitly indicate <code class="sourceCode d">T</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> t0 = Tree!<span class="dt">int</span>(<span class="dv">0</span>); <span class="co">// Yes.</span>

<span class="kw">auto</span> t1 = Tree(<span class="dv">0</span>); <span class="co">// Error, no automatic deduction that T is int.</span></code></pre>
<p>This is because <a href="#templated-constructors">templated constructors</a> are possible and may have template parameters differing from that of the global struct template. But honestly that's a pain, even more so for struct templates with many template arguments. There is a solution, of course: use a template function to create the correct struct and return it. Here is an example of such a factory function for <code class="sourceCode d">Tree</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tree2;
<span class="kw">import</span> tree1;

<span class="kw">auto</span> tree(T)(T value, Tree!T[] children = <span class="kw">null</span>)
{
    <span class="kw">return</span> Tree!(T)(value, children);
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> t0 = tree(<span class="dv">0</span>); <span class="co">// Yes!</span>
    <span class="kw">auto</span> t1 = tree(<span class="dv">1</span>, [t0,t0]); <span class="co">// Yes!</span>

    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( <span class="dt">typeof</span>(t1) == Tree!<span class="dt">int</span> ));

    <span class="kw">auto</span> t2 = tree(t0); <span class="co">// Yes! typeof(t2) == Tree!(Tree!(int))</span>
}</code></pre>
<p>Once more, have a look at <a href="dlang.org/phobos/std_algorithm.html">std.algorithm</a> and <a href="http://dlang.og/phobos/std_range.html">std.range</a>, they show numerous examples of this idiom.</p>
<h3 id="giving-access-to-inner-parameters">Giving Access to Inner Parameters</h3>
<p>As was said in section <a href="#inner-alias">Inner Alias</a>, template arguments are not accessible externally once the template is instantiated. For the <code class="sourceCode d">Tree</code> example, you might want to get an easy access to <code class="sourceCode d">T</code>. As for any other templates, you can expose the parameters by aliasing them. Let's complete our <code class="sourceCode d">Tree</code> definition:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tree3;
<span class="kw">import</span> std.array;

<span class="kw">struct</span> Tree(T)
{
    <span class="kw">alias</span> T Type;
    T value;
    Tree[] children;

    <span class="dt">bool</span> isLeaf() @property { <span class="kw">return</span> children.empty;}
}

<span class="dt">void</span> main()
{
    Tree!<span class="dt">string</span> t0 =Tree!<span class="dt">string</span>(<span class="st">&quot;abc&quot;</span>);
    <span class="kw">alias</span> <span class="dt">typeof</span>(t0) T0;

    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( T0.Type == <span class="dt">string</span> ));
}</code></pre>
<h3 id="templated-member-functions">Templated Member Functions</h3>
<p>A struct template is a template like any other: you can declare templates inside, even function templates. Which means you can have templated member functions.</p>
<blockquote>
<p><strong>Crippled D. </strong> Okay, since I haven't introduce some powerful D features such as <a href="#mixin-templates">mixin templates</a> and <a href="#string-mixins">string mixins</a>, I'll have to do some code duplication here. Sorry for that, but that's the condition for having all named code sample compile.</p>
</blockquote>
<h5 id="mapping-on-a-tree">Mapping on a Tree</h5>
<p>Let us use a templated member function to give our <code class="sourceCode d">Tree</code> a mapping ability. For a range, you can use <a href="http://dlang.org/phobos/std_algorithm.html#map">std.algorithm.map</a> to apply a function in turn to each element, thus delivering a transformed range. The same process can be done for a tree, thereby keeping the overall <em>shape</em> but modifying the elements. We could easily make that a free function, but this <em>is</em> the member function section.</p>
<p>Let's think a little bit about it before coding. <code class="sourceCode d">map</code> should be a function template that accepts any function name as a template alias parameter (like <a href="http://dlang.org/phobos/std_algorithm.html#map">std.algorithm.map</a>). Let's call this alias <code class="sourceCode d">fun</code>. The <code class="sourceCode d">value</code> member should be transformed by <code class="sourceCode d">fun</code>, that's easy to do. We want to return a new <code class="sourceCode d">Tree</code>, which will have as its type parameter the result type of <code class="sourceCode d">fun</code>. If <code class="sourceCode d">fun</code> transforms <code class="sourceCode d">A</code>s into <code class="sourceCode d">B</code>s, then a <code>Tree!A</code> will be mapped to a <code>Tree!B</code>. However, since <code class="sourceCode d">fun</code> can be a function template, it may not have a pre-defined return type that could be obtained by <a href="http://dlang.org/phobos/std_traits.html#ReturnType">std.traits.ReturnType</a>. We will just apply it on a <code class="sourceCode d">T</code> value (obtained by <code>T.init</code> and take this type. So <code class="sourceCode d">B</code> will be <code>typeof(fun(T.init))</code>.</p>
<p>What about the children? We will map <code class="sourceCode d">fun</code> on them too and collect the result into a new children array. They will have the same type: <code>Tree!(B)</code>. If the mapped <code class="sourceCode d">Tree</code> is a leaf (ie: if it has no children), the process will stop.</p>
<p>Since this is a recursive template, we have to help the compiler a bit with the return type. Here we go:<a href="#fn6" class="footnoteRef" id="fnref6"><sup>6</sup></a></p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tree4;
<span class="kw">import</span> std.array;

<span class="kw">auto</span> tree(T)(T value, Tree!T[] children = <span class="kw">null</span>)
{
    <span class="kw">return</span> Tree!(T)(value, children);
}

<span class="kw">struct</span> Tree(T)
{
    <span class="kw">alias</span> T Type;
    T value;
    Tree[] children;

    <span class="dt">bool</span> isLeaf() @property { <span class="kw">return</span> children.empty;}

    Tree!(<span class="dt">typeof</span>(fun(T.<span class="dt">init</span>))) map(<span class="kw">alias</span> fun)()
    {
        <span class="kw">alias</span> <span class="dt">typeof</span>(fun(T.<span class="dt">init</span>)) MappedType;
        MappedType mappedValue = fun(value);
        Tree!(MappedType)[] mappedChildren;
        <span class="kw">foreach</span>(child; children) mappedChildren ~= child.map!(fun);
        <span class="kw">return</span> tree(mappedValue, mappedChildren);
    }
}</code></pre>
<p>Let's use it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_tree4;
<span class="kw">import</span> std.conv;
<span class="kw">import</span> tree4;

<span class="dt">int</span> addOne(<span class="dt">int</span> a) { <span class="kw">return</span> a+<span class="dv">1</span>;}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> t0 = tree(<span class="dv">0</span>);
    <span class="kw">auto</span> t1 = tree(<span class="dv">1</span>, [t0,t0]);
    <span class="kw">auto</span> t2 = tree(<span class="dv">2</span>, [t1, t0, tree(<span class="dv">3</span>)]);

<span class="co">/* t2 is       2</span>
<span class="co">             / | \</span>
<span class="co">            1  0  3</span>
<span class="co">           / \</span>
<span class="co">          0   0</span>
<span class="co">*/</span>

    <span class="co">// t2 is a Tree!(int)</span>
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( t2.Type == <span class="dt">int</span> ));

    <span class="co">// Adding one to all values</span>

    <span class="kw">auto</span> t3 = t2.map!(addOne);

<span class="co">/* t3 is       3</span>
<span class="co">             / | \</span>
<span class="co">            2  1  4</span>
<span class="co">           / \</span>
<span class="co">          1   1</span>
<span class="co">*/</span>

    <span class="kw">assert</span>(t3.value == <span class="dv">3</span>);

    <span class="co">// Converting all values to strings</span>
    <span class="kw">auto</span> ts = t2.map!(to!<span class="dt">string</span>); <span class="co">// we convert every value into a string;</span>

<span class="co">/* ts is      &quot;2&quot;</span>
<span class="co">             / | \</span>
<span class="co">           &quot;1&quot;&quot;0&quot;&quot;3&quot;</span>
<span class="co">           / \</span>
<span class="co">         &quot;0&quot;  &quot;0&quot;</span>
<span class="co">*/</span>

    <span class="kw">assert</span>(<span class="kw">is</span>( ts.Type == <span class="dt">string</span> ));
    <span class="kw">assert</span>(ts.value == <span class="st">&quot;2&quot;</span>);
}</code></pre>
<h5 id="folding-a-tree">Folding a Tree</h5>
<p>You may feel <code class="sourceCode d">map</code> is not really a member function: it does not take any argument. Let's make another transformation on <code class="sourceCode d">Tree</code>s: folding them, that is: collapsing all values into a new one. The range equivalent is <a href="http://dlang.org/phobos/std_algorithm.html#reduce">std.algorithm.reduce</a> which collapses an entire (linear) range into one value, be it a numerical value, another range or what have you</p>
<p>For a tree, folding can for example generate all values in pre-order or post-order, calculate the height of the tree, the number of leaves... As for ranges, folding is an extremely versatile function. It can in fact be used to convert a <code class="sourceCode d">Tree</code> into an array or another <code class="sourceCode d">Tree</code>. We will do just that.</p>
<p>Taking inspiration from <code class="sourceCode d">reduce</code>, we need an seed value and <em>two</em> folding functions. The first one, <code class="sourceCode d">ifLeaf</code>, will be called on childless nodes, for <code class="sourceCode d">fold</code> to return <code>ifLeaf(value, seed)</code>. The second one, <code class="sourceCode d">ifBranch</code>, will be called nodes with children. In this case, we first apply <code class="sourceCode d">fold</code> on all children and then return <code>ifBranch(value, foldedChildren)</code>. In some simple cases, we can use the same function, hence a default case for <code class="sourceCode d">ifBranch</code>. Here is the code:<a href="#fn7" class="footnoteRef" id="fnref7"><sup>7</sup></a></p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tree5;
<span class="kw">import</span> std.array;

Tree!(T) tree(T)(T value, Tree!T[] children = <span class="kw">null</span>)
{
    <span class="kw">return</span> Tree!(T)(value, children);
}

<span class="kw">struct</span> Tree(T)
{
    <span class="kw">alias</span> T Type;
    T value;
    Tree[] children;

    <span class="dt">bool</span> isLeaf() @property { <span class="kw">return</span> children.empty;}

    <span class="dt">typeof</span>(ifLeaf(T.<span class="dt">init</span>, S.<span class="dt">init</span>))
    fold(<span class="kw">alias</span> ifLeaf, <span class="kw">alias</span> ifBranch = ifLeaf, S)(S seed)
    {
        <span class="kw">if</span> (isLeaf)
        {
            <span class="kw">return</span> ifLeaf(value, seed);
        }
        <span class="kw">else</span>
        {
            <span class="dt">typeof</span>(Tree.<span class="dt">init</span>.fold!(ifLeaf, ifBranch)(seed))[] foldedChildren;
            <span class="kw">foreach</span>(child; children)
                foldedChildren ~= child.fold!(ifLeaf, ifBranch)(seed);
            <span class="kw">return</span> ifBranch(value, foldedChildren);
        }
    }
}</code></pre>
<p>Let's play a bit with it. First, we want to sum all values of a tree. For leaves, we just return the node's <code class="sourceCode d">value</code> plus <code class="sourceCode d">seed</code>. For branches, we are given <code class="sourceCode d">value</code> and an array containing the sums of values for all children. We need to sum the values of this array, add it to the node's <code class="sourceCode d">value</code> and return that. In that case, we do not about the seed value.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> summingtree;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> tree5;

<span class="dt">typeof</span>(T.<span class="dt">init</span> + S.<span class="dt">init</span>)
sumLeaf(T, S)(T value, S seed)
{
    <span class="kw">return</span> value + seed;
}

T sumBranch(T)(T value, T[] summedChildren)
{
    <span class="kw">return</span> value + reduce!<span class="st">&quot;a+b&quot;</span>(summedChildren);
}

<span class="kw">import</span> std.stdio;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> t0 = tree(<span class="dv">0</span>);
    <span class="kw">auto</span> t1 = tree(<span class="dv">1</span>, [t0,t0]);
    <span class="kw">auto</span> t2 = tree(<span class="dv">2</span>, [t1, t0, tree(<span class="dv">3</span>)]);

    <span class="dt">int</span> sum = t2.fold!(sumLeaf, sumBranch)(<span class="dv">0</span>);
    <span class="kw">assert</span>(sum == <span class="dv">2</span> + (<span class="dv">1</span> + <span class="dv">0</span> + <span class="dv">0</span>) + (<span class="dv">0</span>) + (<span class="dv">3</span>));
}</code></pre>
<p>In the same family, but a bit more interesting is getting all values for in-order iteration: given a tree node, return an array containing the local value and then the values for all nodes, recursively.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> inordertree;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> tree5;

T[] inOrderL(T, S)(T value, S seed)
{
    <span class="kw">return</span> [value] ~ seed;
}

T[] inOrderB(T)(T value, T[][] inOrderChildren)
{
    <span class="kw">return</span> [value] ~ reduce!<span class="st">&quot;a~b&quot;</span>(inOrderChildren);
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> t0 = tree(<span class="dv">0</span>);
    <span class="kw">auto</span> t1 = tree(<span class="dv">1</span>, [t0,t0]);
    <span class="kw">auto</span> t2 = tree(<span class="dv">2</span>, [t1, t0, tree(<span class="dv">3</span>)]);

    <span class="dt">int</span>[] seed; <span class="co">// empty array</span>
    <span class="kw">auto</span> inOrder = t2.fold!(inOrderL, inOrderB)(seed);
    <span class="kw">assert</span>(inOrder == [<span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">3</span>]);
}</code></pre>
<p>And as a last use, why not build a tree?</p>
<blockquote>
<p><strong>TODO.</strong> Write just that.</p>
</blockquote>
<h3 id="templated-constructors">Templated Constructors</h3>
<p>Struct constructors are member function, so they can be templated too. They need not have the same template parameters as the struct definition:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> templatedconstructors;

<span class="kw">struct</span> S(T)
{
    <span class="kw">this</span>(U)(U u) { <span class="co">/*...*/</span> }
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> s = S!<span class="dt">string</span>(<span class="dv">1</span>); <span class="co">// T is string, U is int.</span>
}</code></pre>
<p>As you can see, <a href="#ifti">IFTI</a> works for constructors. <code class="sourceCode d">U</code> is automatically deduced, though you have to indicate <code class="sourceCode d">T</code> in this case. However, this example is drastically limited: you cannot have any value of type <code class="sourceCode d">U</code> in the struct, because <code class="sourceCode d">U</code> does not exist outside the constructor. A bit more useful would be to collect an alias (a function, for example) and use it to initialize the struct. If it's used only for initialization, it can be discarded afterwards. But then, IFTI is not activated by an alias...</p>
<p>The most interesting use I've seen is to make conversions during the struct's construction:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> holder;
<span class="kw">import</span> std.conv;

<span class="kw">struct</span> Holder(Type)
{
    Type value;

    <span class="kw">this</span>(AnotherType)(AnotherType _value)
    {
        value = to!Type(_value);
    }
}

<span class="dt">void</span> main()
{
    Holder!<span class="dt">int</span> h = Holder!<span class="dt">int</span>(<span class="fl">3.14</span>);
    <span class="kw">assert</span>(h.value == <span class="dv">3</span>);
}</code></pre>
<p>That way, a <code class="sourceCode d">Holder!<span class="dt">int</span></code> can be constructed with any value, but if the conversion is possible, it will always hold an <code class="sourceCode d"><span class="dt">int</span></code>.</p>
<h3 id="inner-structs">Inner Structs</h3>
<p>You can create and return inner structs and use the local template parameters in their definition. We could have a factory function for <code class="sourceCode d">Heap</code> like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> heap2;

<span class="kw">auto</span> heap(<span class="kw">alias</span> predicate, Type)(Type[] values)
{
    <span class="kw">struct</span> Heap
    {
        Type[] values;
        <span class="kw">this</span>(Type[] _values)
        {
            <span class="co">/* some code initializing values using predicate */</span>
        }
        <span class="co">/* more heapy code */</span>
    }

    <span class="kw">return</span> Heap(values); <span class="co">// alias predicate is implicit there</span>
}</code></pre>
<p>In that case, the <code class="sourceCode d">Heap</code> struct is encapsulated inside <code class="sourceCode d">heap</code> and uses the <code class="sourceCode d">predicate</code> alias inside its own engine, but it's not a templated struct itself. I did not use <code class="sourceCode d">Tree</code> as an example, because with recursive types it becomes tricky.</p>
<p>By the way, strangely enough, though you cannot declare 'pure' templates inside functions, you can declare struct templates. Remember the <code class="sourceCode d">adder</code> function in section <a href="#anonymous-function-templates">Anonymous Functions</a>? It didn't need to be templated with one type for each argument, as most of the time when you add numbers, they have more or less the same type. But what about a function that converts its arguments to <code class="sourceCode d"><span class="dt">string</span></code>s before concatenating them?</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> anonymous_error;

<span class="kw">auto</span> concatenate(A)(A a)
{
    <span class="co">/* !! Not legal D code !! */</span>
    <span class="kw">return</span> (B)(B b) { <span class="kw">return</span> to!<span class="dt">string</span>(a) ~ to!<span class="dt">string</span>(b);};
}</code></pre>
<p>The previous example is not legal D code (remember <strong>The Mantra</strong>). Of course, there is a solution: just return a struct with a <a href="#templated-member-functions">templated member function</a>, in that case the <code class="sourceCode d">opCall</code> operator:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> innerconcatenate;
<span class="kw">import</span> std.conv;

<span class="kw">auto</span> concatenate(A)(A a)
{
    <span class="kw">struct</span> Concatenator
    {
        A a;

        <span class="kw">auto</span> opCall(B)(B b) @trusted
        {
            <span class="kw">return</span> to!<span class="dt">string</span>(a) ~ to!<span class="dt">string</span>(b);
        }
    }

    Concatenator c;
    c.a = a; <span class="co">// So as not to activate opCall()</span>

    <span class="kw">return</span> c;
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> c = concatenate(<span class="fl">3.14</span>);
    <span class="kw">auto</span> cc = c(<span class="st">&quot;abc&quot;</span>);
    <span class="kw">assert</span>(cc == <span class="st">&quot;3.14abc&quot;</span>);
}</code></pre>
<p>See section <a href="#operator-overloading">operator overloading</a>.</p>
<p>What about templated inner structs inside struct templates? It's perfectly legal:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> templatedinner;

<span class="kw">struct</span> Outer(O)
{
    O o;

    <span class="kw">struct</span> Inner(I)
    {
        O o;
        I i;
    }

    <span class="kw">auto</span> inner(I)(I i) { <span class="kw">return</span> Inner!(I)(o,i);}
}

<span class="kw">auto</span> outer(O)(O o) { <span class="kw">return</span> Outer!(O)(o);}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> o = outer(<span class="dv">1</span>); <span class="co">// o is an Outer!int;</span>
    <span class="kw">auto</span> i = o.inner(<span class="st">&quot;abc&quot;</span>); <span class="co">// Outer.Outer!(int).Inner.Inner!(string)</span>
}</code></pre>
<h3 id="template-this-parameters">Template This Parameters</h3>
<blockquote>
<p><strong>Unfinished!</strong> Some kind of example would be great here.</p>
</blockquote>
<p>Inside a struct or class template, there is another kind of template parameter: the template this parameter, declared with <code class="sourceCode d"><span class="kw">this</span></code> <code class="sourceCode d">identifier</code>. <code class="sourceCode d">identifier</code> then gets the type of the <code class="sourceCode d"><span class="kw">this</span></code> reference. It's useful mainly for two uses:</p>
<ul>
<li><a href="#mixin-templates">mixin templates</a>, where you do not know the enclosing type beforehand. Please see this section for some examples.</li>
<li>to determine how the type of the <code class="sourceCode d"><span class="kw">this</span></code> reference is qualified (<code class="sourceCode d"><span class="kw">const</span></code>, <code class="sourceCode d"><span class="kw">immutable</span></code>, <code class="sourceCode d">shared</code>, <code class="sourceCode d"><span class="kw">inout</span></code> or unqualified).</li>
</ul>
<h3 id="example-a-concat-flatten-range">Example: a Concat / Flatten Range</h3>
<p>We will use what we've learned about struct templates to create a lazy range that flattens ranges of ranges into linear ranges. Remember the <code class="sourceCode d">flatten</code> function from section <a href="#example-flattening-arrays-and-ranges">Flattening Arrays and Ranges</a>? It worked quite well but was <em>eager</em>, not <em>lazy</em>: given an infinite range (a cycle, for example) it would choke on it. We will here make a lazy flattener.</p>
<p>If you look at the ranges defined in <a href="http://dlang.org/phobos/std_range.html">std.range</a>, you will see that most (if not all) of them are structs. That's the basic way to get laziness in D: the struct holds the iteration state and exposes the basic range primitives. At the very least to be an <em>input range</em> ---the simplest kind of range--- a type must have the following members, be they properties, member functions or manifest constants:</p>
<dl>
<dt>front</dt>
<dd>returns the range's first element.
</dd>
<dt>popFront</dt>
<dd>discards the first element and advances the range by one step.
</dd>
<dt>empty</dt>
<dd>returns <code class="sourceCode d"><span class="kw">true</span></code> if the range has no more elements, <code class="sourceCode d"><span class="kw">false</span></code> otherwise.
</dd>
</dl>
<p>From this simple basis, powerful algorithms can be designed that act on ranges. D defines more refined range concepts by adding other constraints. A <em>forward range</em> adds the <code class="sourceCode d">save</code> member that's used to store a range internal state and allows an algorithm to start again from a saved position. A <em>bidirectional range</em> also has the <code class="sourceCode d">back</code> and <code class="sourceCode d">popBack</code> primitives for accessing the end of the range, and so on.</p>
<p>Here we will begin by creating a simple input range that takes a range of ranges and iterates on the inner elements. Let's begin with the very basics:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> flatten2;

<span class="kw">import</span> std.range;
<span class="kw">import</span> rank2;

<span class="kw">struct</span> Flatten(Range)
{
    Range range;
    <span class="co">/*...*/</span>
}

<span class="kw">auto</span> flatten(Range)(Range range)
{
    <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">0</span>)
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;flatten needs a range.&quot;</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">1</span>)
        <span class="kw">return</span> range;
    <span class="kw">else</span>
        <span class="kw">return</span> Flatten!(Range)(range);
}</code></pre>
<p>So we have a struct template and its associated factory function. It doesn't make sense to instantiate <code class="sourceCode d">Flatten</code> with any old type, so <code class="sourceCode d">Range</code> is checked to be a range, using the <code class="sourceCode d">rank</code> template we saw on <a href="#rank-for-ranges">Rank for Ranges</a>. We haven't seen template constraints yet (they are described in section <a href="#constraints">Constraints</a>), but they would be a good fit here too.</p>
<p>A range of ranges can be represented like this:</p>
<pre class="sourceCode d"><code class="sourceCode d">[ subRange1[elem11, elem12,...]
, subRange2[elem21, elem22,...]
, ... ]</code></pre>
<p>We want <code class="sourceCode d">Flatten</code> to return elements in this order: <code class="sourceCode d">elem11</code>, <code class="sourceCode d">elem12</code>, ... <code class="sourceCode d">elem21</code>, <code class="sourceCode d">elem22</code>, ... Note that for ranges of rank higher than 2, the <code class="sourceCode d">elemxy</code>s are themselves ranges. At any given time, <code class="sourceCode d">Flatten</code> is working on a sub-range, iterating on its elements and discarding it when it's empty. The iteration will stop when the last subrange has been consumed, that is when <code class="sourceCode d">range</code> itself is empty.</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> flatten3;
<span class="kw">import</span> std.range;

<span class="kw">import</span> rank2;

<span class="kw">struct</span> Flatten(Range)
{
    <span class="kw">alias</span> ElementType!Range    SubRange;
    <span class="kw">alias</span> ElementType!SubRange Element;

    Range range;
    SubRange subRange;

    <span class="kw">this</span>(Range _range) {
        range = _range;
        <span class="kw">if</span> (!range.empty) subRange = range.front;
    }

    Element front() { <span class="kw">return</span> subRange.front;}

    <span class="dt">bool</span> empty() { <span class="kw">return</span> range.empty;}

    <span class="dt">void</span> popFront() {
        <span class="kw">if</span> (!subRange.empty) subRange.popFront;
        <span class="kw">while</span>(subRange.empty &amp;&amp; !range.empty) {
            range.popFront;
            <span class="kw">if</span> (!range.empty) subRange = range.front;
        }
    }
}</code></pre></td></tr></table>
<ul>
<li>I cheat a little bit with D standard bracing style, because it eats vertical space like there is no tomorrow.</li>
<li>We begin on line 8 and 9 by defining some new types used by the methods. They are not strictly necessary but make the code easier to understand and expose these types to the outer world, if they are needed.</li>
<li>A constructor is now necessary to initialize the struct.</li>
<li><code class="sourceCode d">front</code> returns a subrange element.</li>
</ul>
<p>But then, this only works for ranges of ranges (of rank &lt; 2). We want something that flattens ranges of any rank down to a linear range. This is easily done, we just add recursion in the factory function:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> flatten4;
<span class="kw">import</span> rank2;
<span class="kw">public</span> <span class="kw">import</span> flatten3;

<span class="kw">auto</span> flatten(Range)(Range range)
{
    <span class="kw">static</span> <span class="kw">if</span>      (rank!Range == <span class="dv">0</span>)
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;flatten needs a range.&quot;</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">1</span>)
        <span class="kw">return</span> range;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">2</span>)
        <span class="kw">return</span> Flatten!(Range)(range);
    <span class="kw">else</span>         <span class="co">// rank 3 or higher</span>
        <span class="kw">return</span> flatten(Flatten!(Range)(range));
}</code></pre>
<p>And, testing:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> using_flatten4;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.range;
<span class="kw">import</span> std.string;
<span class="kw">import</span> rank2;
<span class="kw">import</span> flatten4;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> rank3 = [[[<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>],[<span class="dv">3</span>,<span class="dv">4</span>,<span class="dv">5</span>],[<span class="dv">6</span>] ]
                 ,[[<span class="dv">7</span>],[],[<span class="dv">8</span>,<span class="dv">9</span>],[<span class="dv">10</span>,<span class="dv">11</span>]]
                 ,[[],[<span class="dv">12</span>]             ]
                 ,[[<span class="dv">13</span>]                ]];

    <span class="kw">auto</span> rank1 = flatten(rank3);
    <span class="kw">assert</span>(rank!(<span class="dt">typeof</span>(rank1)) == <span class="dv">1</span>); <span class="co">// Yup, it&#39;s a linear range</span>
    <span class="kw">assert</span>(equal( rank1, [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>,<span class="dv">5</span>,<span class="dv">6</span>,<span class="dv">7</span>,<span class="dv">8</span>,<span class="dv">9</span>,<span class="dv">10</span>,<span class="dv">11</span>,<span class="dv">12</span>,<span class="dv">13</span>] ));

    <span class="kw">auto</span> stillRank1 = flatten(rank1);
    <span class="kw">assert</span>(equal( stillRank1, rank1 )); <span class="co">// No need to insist</span>

    <span class="kw">auto</span> text =
   <span class="st">&quot;Sing, O goddess, the anger of Achilles son of Peleus,</span>
<span class="st">    that brought countless ills upon the Achaeans.</span>
<span class="st">    Many a brave soul did it send hurrying down to Hades,</span>
<span class="st">    and many a hero did it yield a prey to dogs and vultures,</span>
<span class="st">    for so were the counsels of Jove fulfilled</span>
<span class="st">    from the day on which the son of Atreus, king of men,</span>
<span class="st">    and great Achilles, first fell out with one another.&quot;</span>;

    <span class="kw">auto</span> lines = text.splitLines;   <span class="co">// array of strings</span>
    <span class="dt">string</span>[][] words;
    <span class="kw">foreach</span>(line; lines) words ~= array(splitter(line, <span class="ch">&#39; &#39;</span>));
    <span class="kw">assert</span>( rank!(<span class="dt">typeof</span>(words)) == <span class="dv">3</span>); <span class="co">// range of range of strings</span>
                                        <span class="co">// range of range of array of chars</span>
    <span class="kw">auto</span> flat = flatten(words);

    <span class="kw">assert</span>(equal(take(flat, <span class="dv">50</span>),
             <span class="st">&quot;Sing,Ogoddess,theangerofAchillessonofPeleus,thatbr&quot;</span>));
}</code></pre>
<p>Here it is. It works and we used a <a href="#struct-templates">struct template</a>, <a href="#static-if">static if</a>, <a href="#inner-alias">inner member alias</a>), <a href="#factory-functions">factory functions</a> and <a href="#ifti">IFTI</a>.</p>
<h2 id="class-templates">Class Templates</h2>
<blockquote>
<p><strong>This Section Needs You!</strong> I'm not an OOP programmer and am not used to create interesting hierarchies. If anyone reading this has an example of class templates that could be used throughout the section, I'm game.</p>
</blockquote>
<h3 id="syntax-4">Syntax</h3>
<p>No surprise here, just put the template parameters list between <code class="sourceCode d"><span class="kw">class</span></code> and the optional inheritance indication:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> classsyntax1;

<span class="kw">class</span> Base {}
<span class="kw">interface</span> Interface1 {}
<span class="kw">interface</span> Interface2 {}

<span class="kw">class</span> MyClass(Type, <span class="kw">alias</span> fun, <span class="dt">bool</span> b = <span class="kw">false</span>)
    : Base, Interface1, Interface2
{ <span class="co">/*...*/</span> }</code></pre>
<p>What's more fun is that you can have parameterized inheritance: the various template parameters are defined before the base class list, you can use them here:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> classsyntax2;

<span class="kw">class</span> Base(T) {}
<span class="kw">interface</span> Interface1 {}
<span class="kw">interface</span> Interface2(<span class="kw">alias</span> fun, <span class="dt">bool</span> b) {}

<span class="kw">class</span> MyClass(Type, <span class="kw">alias</span> fun, <span class="dt">bool</span> b = <span class="kw">false</span>)
    : Base!(Type), Interface1, Interface2!(fun,b)
{ <span class="co">/*...*/</span> }</code></pre>
<blockquote>
<p><strong>Interface Templates?</strong> Yes you can. See section <a href="#other-templates">Other Templates</a></p>
</blockquote>
<p>This opens interesting vistas, where what a class inherits is determined by its template arguments (since <code class="sourceCode d">Base</code> may be many different classes or even interfaces depending on <code class="sourceCode d">Type</code>). In fact, look at this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> classsyntax3;

<span class="kw">enum</span> WhatBase { <span class="dt">Object</span>, <span class="dt">Interface</span>, BaseClass }

<span class="kw">template</span> Base(WhatBase whatBase = WhatBase.<span class="dt">Object</span>)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == WhatBase.<span class="dt">Object</span>))
        <span class="kw">alias</span> <span class="dt">Object</span> Base; <span class="co">// MyClass inherits directly from Object</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span>(<span class="kw">is</span>(T == WhatBase.<span class="dt">Interface</span>))
        <span class="kw">alias</span> TheInterface Base;
    <span class="kw">else</span>
        <span class="kw">alias</span> TheBase Base;
}

<span class="kw">class</span> MyClass(Type) : Base!Type {}</code></pre>
<p>With this, <code class="sourceCode d">MyClass</code> can inherit from <code class="sourceCode d"><span class="dt">Object</span></code>, the root of D's class hierarchy, from an interface, or from another class. Obviously, the dispatching template could be much more refined. With a second template parameter, the base class could itself be parameterized, and so on.</p>
<p>What this syntax <em>cannot</em> do however is change the number of interfaces at compile-time.<a href="#fn8" class="footnoteRef" id="fnref8"><sup>8</sup></a> It's complicated to say: 'with <em>this</em> argument, <code class="sourceCode d">MyClass</code> will inherit from <code class="sourceCode d">I</code>, <code class="sourceCode d">J</code> and <code class="sourceCode d">K</code> and with <em>that</em> argument, it will inherit only from <code class="sourceCode d">L</code>.' You'd need the previous interfaces to all participate in the action, to all be templates and such. If the needed interfaces are all pre-defined and not templated, you need wrapping templates. It's a pain. However, type tuples can be used to greatly simplify this.</p>
<h3 id="methods-templates">Methods Templates</h3>
<p>An object's methods are nothing more than delegates with a reference to the local <code class="sourceCode d"><span class="kw">this</span></code> context. As seen for structs <a href="#templated-member-functions">methods can be templates too</a>.</p>
<blockquote>
<p><strong>Unfinished!</strong> I need to write something on overriding methods with templates. Also, I need to find some interesting method example. Man, I do not do classes.</p>
</blockquote>
<h3 id="invariant-clauses"><code>invariant</code> clauses</h3>
<p>In the same family than <code class="sourceCode d"><span class="kw">in</span></code>/<code class="sourceCode d"><span class="kw">out</span></code> clauses for functions (section [inandoutclauses]), a class template's <code class="sourceCode d"><span class="kw">invariant</span></code> clause has access to the template parameter. You cannot make it disappear totally, but you can get it to be empty with a <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> statement.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> classinvariant;

<span class="kw">class</span> MyClass(T, U, V)
{
    <span class="co">/*...*/</span>

    <span class="kw">invariant</span> ()
    {
        <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T == U))
        {
            <span class="co">/* invariant code */</span>
        }
        <span class="kw">else</span>
        { } <span class="co">/* empty invariant */</span>
    }
}</code></pre>
<h3 id="inner-classes">Inner Classes</h3>
<p>It's the same principle as for <a href="#inner-structs">structs</a>. You can define inner classes using the template parameters. You can even give them method templates that use other template arguments. There is really nothing different from inner structs.</p>
<h3 id="anonymous-classes">Anonymous Classes</h3>
<p>In D, you can return anonymous classes directly from a function or a method. Can these be templated? Well, they cannot be class templates, that wouldn't make sense. But you can return anonymous classes with templated methods, if you really need to.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> anonymousclass;

<span class="co">// stores a function and a default return value.</span>
<span class="kw">auto</span> acceptor(<span class="kw">alias</span> fun, D)(D defaultValue)
{
    <span class="kw">return</span> <span class="kw">new</span> <span class="kw">class</span>
    {
        <span class="kw">this</span>() {}

        <span class="kw">auto</span> opCall(T)(T t)
        {
            <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, fun(T.<span class="dt">init</span>)))
                <span class="kw">return</span> fun(t);
            <span class="kw">else</span>
                <span class="kw">return</span> defaultValue;
        }
    };
}

<span class="kw">unittest</span>
{
    <span class="dt">int</span> add1(<span class="dt">int</span> i) { <span class="kw">return</span> i+<span class="dv">1</span>;}
    <span class="kw">auto</span> accept = acceptor!(add1)(-<span class="dv">1</span>);

    <span class="kw">auto</span> test1 = accept(<span class="dv">10</span>);
    <span class="kw">assert</span>(test1 == <span class="dv">11</span>);

    <span class="kw">auto</span> test2 = accept(<span class="st">&quot;abc&quot;</span>);
    <span class="kw">assert</span>(test2 == -<span class="dv">1</span>); <span class="co">// default value</span>
}</code></pre>
<p>For <code class="sourceCode d">__traits(compiles, ...)</code>, see <a href="www.dlang.org/traits.html">here</a> online and section <a href="#traits">__traits</a> in this document.</p>
<h3 id="parametrized-base-class">Parametrized Base Class</h3>
<p>You can use a template parameter directly as a base class:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> parametrizedbaseclass;

<span class="kw">interface</span> ISerializable
{
    <span class="dt">size_t</span> serialize() @property;
}

<span class="kw">class</span> Serializable(T) : T, ISerializable
{
    <span class="dt">size_t</span> serialize() @property
    {
        <span class="kw">return</span> <span class="kw">this</span>.tohash;
    }
}</code></pre>
<p>In this example, a <code class="sourceCode d">Serializable!SomeClass</code> can act as a <code class="sourceCode d">SomeClass</code>. It's not different from what you would do with normal classes except the idiom is now abstracted on the base class: you write the template once, it can then be used on any class.</p>
<p>If you have different interfaces like this, you can nest these properties:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> wrapped = <span class="kw">new</span> Serializable!(Iterable!(SomeClass))(<span class="co">/*...*/</span>);</code></pre>
<p>Of course, the base class and the interface may themselves be parameterized:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> serializetemplate;

<span class="kw">enum</span> SerializationPolicy { policy1, policy2 }

<span class="kw">interface</span> ISerializable
(SerializationPolicy policy = SerializationPolicy.policy1)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(policy == SerializationPolicy.policy1))
        <span class="dt">void</span> serialize() { <span class="co">/*...*/</span> }
    <span class="kw">else</span>
        <span class="dt">void</span> serialize() { <span class="co">/*...*/</span> }
}

<span class="kw">class</span> Serializable(T, Policy) : T, ISerializable!Policy
{
    <span class="co">/*...*/</span>
}</code></pre>
<p>In D, you can also get this kind of effect with an `alias X this;} declaration in your class or struct. You should also have a look at <a href="#mixin-templates">mixin templates</a> and <a href="#wrapper-templates">wrapper templates</a> for other idioms built around the same need.</p>
<h3 id="adding-functionalities-through-inheritance">Adding Functionalities Through Inheritance</h3>
<p>Here is an example taken from Timon Gehr. Given a base class <code class="sourceCode d">Cell</code> with a private field and get/set methods, it's possible to provide additional functionalities through inheritance. By defining templates for <code class="sourceCode d">Cell</code> subclasses, each with a new possibility (doubling the value, logging the value, etc.), it's possible to select those new actions by inheritance:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/**</span>
<span class="co"> * Timon Gehr timon.gehr@gmx.ch via puremagic.com</span>
<span class="co"> */</span>
<span class="kw">module</span> inheritanceexample;

<span class="kw">import</span> std.stdio;

<span class="kw">abstract</span> <span class="kw">class</span> Cell(T)
{
    <span class="kw">abstract</span> <span class="dt">void</span> set(T value);
    <span class="kw">abstract</span> <span class="kw">const</span>(T) get();
<span class="kw">private</span>:
    T field;
}

<span class="kw">class</span> AddSetter(C: Cell!T,T): C
{
    <span class="kw">override</span> <span class="dt">void</span> set(T value){field = value;}
}

<span class="kw">class</span> AddGetter(C: Cell!T,T): C
{
    <span class="kw">override</span> <span class="kw">const</span>(T) get(){<span class="kw">return</span> field;}
}

<span class="kw">class</span> DoubleCell(C: Cell!T,T): C
{
    <span class="kw">override</span> <span class="dt">void</span> set(T value){<span class="kw">super</span>.set(<span class="dv">2</span>*value);}
}

<span class="kw">class</span> OneUpCell(C: Cell!T,T): C
{
    <span class="kw">override</span> <span class="dt">void</span> set(T value){<span class="kw">super</span>.set(value+<span class="dv">1</span>);}
}

<span class="kw">class</span> SetterLogger(C:Cell!T,T): C
{
    <span class="kw">override</span> <span class="dt">void</span> set(T value)
    {
        <span class="kw">super</span>.set(value);
        writeln(<span class="st">&quot;cell has been set to &#39;&quot;</span>,value,<span class="st">&quot;&#39;!&quot;</span>);
    }
}

<span class="kw">class</span> GetterLogger(C:Cell!T,T): C
{
    <span class="kw">override</span> <span class="kw">const</span>(T) get()
    {
        <span class="kw">auto</span> value = <span class="kw">super</span>.get();
        writeln(<span class="st">&quot;&#39;&quot;</span>,value,<span class="st">&quot;&#39; has been retrieved!&quot;</span>);
        <span class="kw">return</span> value;
    }
}

<span class="co">// ConcreteCell has a &#39;true&#39; getter and a &#39;true&#39; setter</span>
<span class="kw">class</span> ConcreteCell(T): AddGetter!(AddSetter!(Cell!T)){}

<span class="co">// OneUpDoubleSetter has a setter that adds 1 to the stored value</span>
<span class="co">// and then doubles it</span>
<span class="kw">class</span> OneUpDoubleSetter(T): OneUpCell!(DoubleCell!(AddSetter!(Cell!T))){}

<span class="co">// doubleOneUpSetter has a setter that doubles the stored value and add 1</span>
<span class="kw">class</span> DoubleOneUpSetter(T): DoubleCell!(OneUpCell!(AddSetter!(Cell!T))){}

<span class="dt">void</span> main()
{
    Cell!<span class="dt">string</span> x;
    x = <span class="kw">new</span> ConcreteCell!<span class="dt">string</span>;
    x.set(<span class="st">&quot;hello&quot;</span>);
    writeln(x.get());

    Cell!<span class="dt">int</span> y;
    y = <span class="kw">new</span> SetterLogger!(ConcreteCell!<span class="dt">int</span>);
    y.set(<span class="dv">123</span>); <span class="co">// prints: &quot;cell has been set to &#39;123&#39;!</span>

    y = <span class="kw">new</span> GetterLogger!(DoubleCell!(ConcreteCell!<span class="dt">int</span>));
    y.set(<span class="dv">1234</span>);
    y.get(); <span class="co">// prints &quot;&#39;2468&#39; has been retrieved!&quot;</span>

    y = <span class="kw">new</span> AddGetter!(OneUpDoubleSetter!<span class="dt">int</span>);
    y.set(<span class="dv">100</span>);
    writeln(y.get()); <span class="co">// prints &quot;202&quot;</span>
    y = <span class="kw">new</span> AddGetter!(DoubleOneUpSetter!<span class="dt">int</span>);
    y.set(<span class="dv">100</span>);
    writeln(y.get()); <span class="co">// prints &quot;201&quot;</span>
}</code></pre>
<p>For those of you knowing the Scala programming language, this is a bit reminiscent of <em>traits</em>, which in Scala are sort-of stub classes that can be added to other classes to provide new functions. In D, apart from the above feature, you can also use <a href="#mixin-templates">mixin templates</a> and <a href="#string-mixins">string mixins</a>.</p>
<h3 id="the-curiously-recurring-template-pattern">The Curiously Recurring Template Pattern</h3>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> crtp;

<span class="kw">class</span> Base(Child) { <span class="co">/*...*/</span> }

<span class="kw">class</span> Derived : Base!Derived { <span class="co">/*...*/</span> }</code></pre>
<p>Hold on, what does that mean? <code class="sourceCode d">Base</code> is easy to understand. But what about <code class="sourceCode d">Derived</code>? It says it inherits from another class that is templated on... <code class="sourceCode d">Derived</code> <em>itself</em>? But <code class="sourceCode d">Derived</code> is not defined at this stage! Or is it? Yes, that works. It's called CRTP, which stands for Curiously Recurring Template Pattern (see <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern">Wikipedia</a> on this). But what could be the interest of such a trick?</p>
<p>As you can see in the Wikipedia document it's used either to obtain a sort of compile-time binding or to inject code in your derived class. For the latter, D offers <a href="#mixin-templates">mixin templates</a> which you should have a look at. CRTP comes from C++ where you have multiple inheritance. In D, I fear it's not so interesting. Feel free to prove me wrong, I'll gladly change this section.</p>
<h3 id="example-automatic-dynamic-dispatch">Example: Automatic Dynamic Dispatch</h3>
<p>This example comes from Andrej Mitrovic. You can also find it on the D wiki: <a href="http://wiki.dlang.org/Dispatching_an_object_based_on_its_dynamic_type">http://wiki.dlang.org/Dispatching_an_object_based_on_its_dynamic_type</a>.</p>
<p>Sometimes you may need to call a function with an object where the function only accepts a certain derived object type. In such a case you need to ensure that the dynamic type of an object is of a specific type before attempting to cast it to that type and passing it over to a function. For example:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">class</span> A { }
<span class="kw">class</span> B : A { }
<span class="kw">class</span> C : A { }

<span class="dt">void</span> foo(B b) { }
<span class="dt">void</span> foo(C c) { }

<span class="dt">void</span> main()
{
    A b = <span class="kw">new</span> B;
    A c = <span class="kw">new</span> C;

    foo(b);  <span class="co">// not accepted, object must be casted to either B or C</span>
    foo(c);  <span class="co">// ditto</span>
}</code></pre>
<p>Since the objects <code>b</code> and <code>c</code> of static type <code>A</code> could be of any dynamic type derived from class <code>A</code>, the user would have to try and cast the objects to know whether they can call <code>foo</code> with such objects. The code to do the dispatching mechanism by hand would typically look like:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.stdio;

<span class="kw">class</span> A { }
<span class="kw">class</span> B : A { }
<span class="kw">class</span> C : A { }

<span class="dt">void</span> foo(B b) { writeln(<span class="st">&quot;called foo(B b);&quot;</span>); }
<span class="dt">void</span> foo(C c) { writeln(<span class="st">&quot;called foo(C c);&quot;</span>); }

<span class="dt">void</span> main()
{
    A b = <span class="kw">new</span> B;
    A c = <span class="kw">new</span> C;
 
    <span class="kw">if</span> (<span class="kw">auto</span> obj = <span class="kw">cast</span>(C)b)
        foo(obj);
    <span class="kw">else</span> <span class="kw">if</span> (<span class="kw">auto</span> obj = <span class="kw">cast</span>(B)b)
        foo(obj);
 
    <span class="kw">if</span> (<span class="kw">auto</span> obj = <span class="kw">cast</span>(C)c)
        foo(obj);
    <span class="kw">else</span> <span class="kw">if</span> (<span class="kw">auto</span> obj = <span class="kw">cast</span>(B)b)
        foo(obj);
}</code></pre>
<p>However this is both inefficient and hard to type, it introduces copy-pasted code, and is error-prone since adding a new leaf class means the user has to inspect and edit the dispatch code. An alternative method is to use the <code>classinfo</code> structure (retrieved via <code>typeid()</code>) associated with every instantiated object, and to compare this to all existing classinfo structs. Once we have a match we can safely do a static cast of an object and pass it to a function.</p>
<p>With the help of templates we can automate the entire process. The only information such a template needs is the list of leaf classes so it can construct a tree class to properly dispatch the object. A full implementation is provided here:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.stdio;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.string;

<span class="kw">template</span> ClassTreeImpl(Leaves...)
{
    <span class="kw">static</span> <span class="kw">if</span> (Leaves.<span class="dt">length</span> &gt; <span class="dv">1</span>)
    {
        <span class="kw">alias</span> TypeTuple!(Leaves[<span class="dv">0</span>], BaseClassesTuple!(Leaves[<span class="dv">0</span>]),
                         ClassTreeImpl!(Leaves[<span class="dv">1</span>..$])) ClassTreeImpl;
    }
    <span class="kw">else</span>
    <span class="kw">static</span> <span class="kw">if</span> (Leaves.<span class="dt">length</span> == <span class="dv">1</span>)
    {
        <span class="kw">alias</span> TypeTuple!(Leaves[<span class="dv">0</span>], BaseClassesTuple!(Leaves[<span class="dv">0</span>])) ClassTreeImpl;
    }
    <span class="kw">else</span>
    {
        <span class="kw">alias</span> TypeTuple!() ClassTreeImpl;
    }
}

<span class="kw">template</span> ClassTree(Leaves...)
{
    <span class="kw">alias</span> DerivedToFront!(NoDuplicates!(ClassTreeImpl!(Leaves))) ClassTree;
}

<span class="kw">template</span> AutoDispatch(Leaves...)
{
    <span class="dt">void</span> AutoDispatch(<span class="kw">alias</span> func, Args...)(Args args)
        <span class="kw">if</span> (Args.<span class="dt">length</span> &gt;= <span class="dv">1</span> &amp;&amp; <span class="kw">is</span>(Args[<span class="dv">0</span>] == <span class="kw">class</span>))
    {
        <span class="kw">auto</span> objInfo = <span class="kw">typeid</span>(args[<span class="dv">0</span>]);
        <span class="kw">foreach</span> (Base; ClassTree!Leaves)
        {
            <span class="kw">if</span> (objInfo == Base.classinfo)
            {
                <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, { <span class="co">// avoid CT errors due to unrolled static foreach</span>
                    <span class="kw">return</span> func(<span class="kw">cast</span>(Base)(<span class="kw">cast</span>(<span class="dt">void</span>*)args[<span class="dv">0</span>]), args[<span class="dv">1</span>..$]); }() ))
                {
                    <span class="kw">return</span> func(<span class="kw">cast</span>(Base)(<span class="kw">cast</span>(<span class="dt">void</span>*)args[<span class="dv">0</span>]), args[<span class="dv">1</span>..$]);
                }
            }
        }

        <span class="dt">string</span>[] arguments;
        arguments ~= objInfo.toString();
        <span class="kw">foreach</span> (arg; args[<span class="dv">1</span>..$])
            arguments ~= <span class="dt">typeof</span>(arg).<span class="dt">stringof</span>;

        <span class="kw">assert</span>(<span class="dv">0</span>, format(<span class="st">&quot;function &#39;%s&#39; is not callable with types &#39;(%s)&#39;&quot;</span>,
                         __traits(identifier, func), arguments.join(<span class="st">&quot;, &quot;</span>)));
    }
}

<span class="kw">class</span> A { }
<span class="kw">class</span> B : A { }
<span class="kw">class</span> C : B { }
<span class="kw">class</span> D : B { }

<span class="dt">void</span> foo(C c, <span class="dt">int</span> x) { writefln(<span class="st">&quot;foo(C) : received %s&quot;</span>, x); }
<span class="dt">void</span> foo(D d, <span class="dt">int</span> x, <span class="dt">int</span> y) { writefln(<span class="st">&quot;foo(D) : received %s %s&quot;</span>, x, y); }

<span class="dt">void</span> main()
{
    A c = <span class="kw">new</span> C;
    A d = <span class="kw">new</span> D;
    A a = <span class="kw">new</span> A;

    <span class="kw">alias</span> AutoDispatch!(C, D) callFunc;

    callFunc!foo(c, <span class="dv">1</span>);    <span class="co">// ok</span>
    callFunc!foo(d, <span class="dv">2</span>, <span class="dv">3</span>); <span class="co">// ok</span>
    callFunc!foo(a, <span class="dv">3</span>);    <span class="co">// will assert at runtime</span>
}</code></pre>
<p><code>AutoDispatch</code> takes a list of leaf classes, and extracts the tree class by using the traits found in <a href="http://dlang.org/phobos/std_traits.html">std.traits</a>. The inner <code>AutoDispatch</code> function can then be used to dispatch an object and any additional arguments to a function. The implementation only works for single-object arguments, but a more general solution that dispatches multiple objects is possible to implement.</p>
<h2 id="other-templates">Other Templates?</h2>
<p>Two other aggregate types in D can be templated using the same syntax: interfaces and unions.</p>
<h3 id="interface-templates">Interface Templates</h3>
<p>The syntax is exactly what you might imagine:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> interfacesyntax;

<span class="kw">interface</span> Interf(T)
{
    T foo(T);
    T[] bar(T,<span class="dt">int</span>);
}</code></pre>
<p>Templated interfaces are sometimes useful but as they look very much like class templates, I won't describe them. As before, remember The Mantra: interface templates are <em>not</em> interfaces, they are a blueprint to produce interfaces at your leisure.</p>
<h3 id="union-templates">Union Templates</h3>
<p>Here is the syntax, no suprise there:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> unionsyntax;

<span class="kw">union</span> Union(A,B,C) { A a; B b; C c;}</code></pre>
<p>Union templates seem like a good idea, but honestly I've never seen one. Any reader of this document, please give me an example if you know one.</p>
<h3 id="enumeration-templates">Enumeration Templates?</h3>
<p>Strangely, enumerations do not have the previous simplified syntax. To declare a templated enumeration, use the eponymous template trick:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> enumsyntax;

<span class="kw">template</span> Enum(T)
{
    <span class="kw">enum</span> Enum : T { A, B, C}
}</code></pre>
<h1 id="some-more-advanced-considerations">Some More Advanced Considerations</h1>
<p>In the previous part, we saw what everyone should know about D templates. But in fact, there is much more to them than that. What follows is not necessarily more complicated, but it's probably a little less commonly used. As this document matures, some subjects may flow from <a href="#basics">Basics</a> into <a href="#some-more-advanced-considerations">Advanced</a> and the other way round.</p>
<h2 id="constraints">Constraints</h2>
<p>Template constraints are a way to block a template instantiation if some condition is not met. Any condition that can be determined at compile-time is authorized, which makes constraints a superset of <a href="#templates-specializations">template specializations</a>. As such, their usage grew rapidly once they were introduced and, if Phobos is any indication, templates specializations are on the contrary becoming less common.</p>
<h3 id="syntax-5">Syntax</h3>
<p>To obtain a constraint, put an <code class="sourceCode d"><span class="kw">if</span></code> clause just after the template parameter list, and before the enclosed scope:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> templateName(T,U,V) <span class="kw">if</span> (someCondition on T, U or V)
{
   ...
}</code></pre>
<p>When the compiler tries to instantiate a template, if will first check the constraint. If it evaluates to <code class="sourceCode d"><span class="kw">false</span></code>, the template declaration is not part of the considered set. That way, using constraints, you can keep or drop templates at your leasure. <code class="sourceCode d"><span class="kw">is</span></code> expressions are your friend there, allowing you to get compile-time introspection on types. See the appendix on <a href="#the-is-expression">is expression</a> for a crash course on it.</p>
<p>You may have many template declarations with the same name and differing constraints (in fact, that's the very use case for constraints). Depending on the activated constraints, some or all will be considered by the compiler.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> constrained;

<span class="kw">template</span> Constrained(T)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>)) { <span class="co">/*...*/</span> } <span class="co">// #1</span>
<span class="kw">template</span> Constrained(T)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">string</span>)) { <span class="co">/*...*/</span> } <span class="co">// #2</span>
<span class="kw">template</span> Constrained(T,U)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>) &amp;&amp; !<span class="kw">is</span>(U : <span class="dt">float</span>)) { <span class="co">/*...*/</span> } <span class="co">// #3</span>
<span class="kw">template</span> Constrained(T,U)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>) &amp;&amp; <span class="kw">is</span>(U : <span class="dt">float</span>)) { <span class="co">/*...*/</span> } <span class="co">// #4</span>

<span class="kw">alias</span> Constrained!(<span class="dt">int</span>) C1;       <span class="co">// #1</span>
<span class="co">// alias Constrained!(string) C2; // Error, no declaration fits (string)</span>
<span class="kw">alias</span> Constrained!(<span class="dt">int</span>,<span class="dt">string</span>) C3;<span class="co">// #3 and #4 considered, but #4 is dropped.</span>
                                  <span class="co">// So #3 it is.</span></code></pre>
<p>This syntax is the same for the special-cases templates seen in sections <a href="#function-templates">Function Templates</a>, <a href="#struct-templates">Struct Templates</a>, <a href="#class-templates">Class Templates</a> and <a href="#other-templates">Other Templates</a>. The only tricky part is for class templates, where you may wonder where to put the constraint: before or after the inheritance list? The answer is: before.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> constraintsyntax;

T theFunction(T)(T argument)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>) || <span class="kw">is</span>(T : <span class="dt">double</span>))
{ <span class="kw">return</span> argument; }

<span class="kw">struct</span> TheStruct(T)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>) || <span class="kw">is</span>(T : <span class="dt">double</span>))
{ <span class="co">/*...*/</span> }

<span class="kw">class</span> TheClass(T)
    <span class="kw">if</span> (<span class="kw">is</span>(T : <span class="dt">int</span>) || <span class="kw">is</span>(T : <span class="dt">double</span>))
    : BaseClass!T, Interface1
{ <span class="co">/*...*/</span> }</code></pre>
<p>When you write constraints, just remember they are a compile-time construct. For <code class="sourceCode d">theFunction</code>, <code class="sourceCode d">argument</code> is not known at compile-time, only its type, <code class="sourceCode d">T</code>. Do not use <code class="sourceCode d">argument</code> in your constraint. If you need a value of type <code class="sourceCode d">T</code>, use <code class="sourceCode d">T.<span class="dt">init</span></code>. For example:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> ctvalue;

<span class="kw">auto</span> callTwice(<span class="kw">alias</span> fun, T)(T arg)
    <span class="co">// Is it OK to do fun(fun(some T))?</span>
    <span class="kw">if</span> (<span class="kw">is</span>(<span class="dt">typeof</span>({
                      fun(fun(T.<span class="dt">init</span>));
                  }())))
{
    <span class="kw">return</span> fun(fun(arg));
}</code></pre>
<h3 id="constraints-usage">Constraints Usage</h3>
<p>Constraints come from the same idea as C++0x <code class="sourceCode d">concept</code>, er..., concept, although simpler to define, understand and, as shown by D, implement. The idea is to define a set of conditions a type must respect to be a representative of a `concept', and check for it before instantiating.</p>
<p>Have a look at constraints poster-child: <em>ranges</em>.<a href="#fn9" class="footnoteRef" id="fnref9"><sup>9</sup></a> They were rapidly described in section <a href="#example-flattening-arrays-and-ranges">flatten</a>.</p>
<p><a href="http://dlang.org/phobos/std_range.html">std.range</a> defines a set of templates that check the different ranges concepts, called <code class="sourceCode d">isInputRange</code>, <code class="sourceCode d">isForwardRange</code>... I call these <code class="sourceCode d"><span class="dt">bool</span></code>-becoming templates <em>predicate templates</em> and talk about them in <a href="#predicate-templates">this section</a>. Usage is quite simple:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> rangewrapper;
<span class="kw">import</span> std.range;

<span class="kw">struct</span> RangeWrapper(Range)
    <span class="co">// Does Range comply with the input range &#39;concept&#39;?</span>
    <span class="kw">if</span> (isInputRange!Range)
{
   <span class="co">/* Here we know that Range has at least three member functions:</span>
<span class="co">      .front(), .popFront() and .empty(). We can use them happily.*/</span>
}

<span class="co">// In the factory function too.</span>
<span class="kw">auto</span> rangeWrapper(Range)(Range range) <span class="kw">if</span> (isInputRange!Range)
{
    <span class="kw">return</span> RangeWrapper!(Range)(range);
}</code></pre>
<p>In fact, it's a bit like a compile-time interface or compile-time duck-typing: we do <em>not</em> care about <code class="sourceCode d">Range</code>'s 'kind': it may by a <code class="sourceCode d"><span class="kw">struct</span></code> or a <code class="sourceCode d"><span class="kw">class</span></code> for all we know. What is important is that it respects the <em>input range</em> concept.</p>
<p>The good news is that the compiler will complain when it cannot instantiate a template due to constraints being not respected. It gives better error messages this way (although not as good as you might need).</p>
<h3 id="constraints-limits">Constraints Limits</h3>
<p>The main problem is that, compared to templates specializations, you cannot do:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> constraints_error;

<span class="kw">template</span> Temp(T)
<span class="kw">if</span> (<span class="kw">is</span>(T:<span class="dt">int</span>))   <span class="co">// #1, specialized for ints</span>
{ <span class="co">/*...*/</span> }

<span class="kw">template</span> Temp(T) <span class="co">// #2, generic case</span>
{ <span class="co">/*...*/</span> }

<span class="kw">alias</span> Temp!<span class="dt">int</span> TI;<span class="co">// Error!</span></code></pre>
<p>Why an error? Because the compiler finds that both the <code class="sourceCode d"><span class="dt">int</span></code>-specialized and the generic version can be instantiated. It cannot decide which one you mean and, quite correctly, does nothing, humble code that it is. No problem, says you, we will just add a constraint to the generic version:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> Temp(T) <span class="kw">if</span> (<span class="kw">is</span>(T:<span class="dt">int</span>)) <span class="co">// #1</span>
{ ... } <span class="co">// specialized for ints</span>

<span class="kw">template</span> Temp(T) <span class="kw">if</span> (!<span class="kw">is</span>(T:<span class="dt">int</span>))<span class="co">// #2</span>
{ ... } <span class="co">// generic case</span>

Temp!<span class="dt">int</span> <span class="co">// Works!</span></code></pre>
<p>Now, when you try to instantiate with an <code class="sourceCode d"><span class="dt">int</span></code>, template #2 is not present (its constraint is false and was dropped from the considered template list) and we can have #1. Hurrah? Not quite. The #1-constraint wormed its way into the generic version, adding code where none was initially. Imagine you had not one, but three different specialized versions:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> Temp(T) <span class="kw">if</span> (<span class="kw">is</span>(T:<span class="dt">int</span>[])) <span class="co">// #1a</span>
{ ... } <span class="co">// specialized for arrays of ints</span>

<span class="kw">template</span> Temp(T) <span class="kw">if</span> (isRange!T) <span class="co">// #1b</span>
{ ... } <span class="co">// specialized for ranges</span>

<span class="kw">template</span> Temp(T) <span class="kw">if</span> (<span class="kw">is</span>(T:<span class="dt">double</span>[n], <span class="dt">int</span> n)) <span class="co">// #1c</span>
{ ... } <span class="co">// specialized for static arrays of double</span>

<span class="kw">template</span> Temp(T) <span class="co">// #2, generic</span>
   <span class="kw">if</span> ( <span class="co">/* What constraint? */</span>
{ ... }</code></pre>
<p>OK, quick: what constraint for #2? The complement to <em>all</em> other constraints. See:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> Temp(T) <span class="co">// #2, generic</span>
   <span class="kw">if</span> ( !(<span class="kw">is</span>(T:<span class="dt">int</span>[]))
     &amp;&amp; !isRange!T
     &amp;&amp; !<span class="kw">is</span>(T:<span class="dt">double</span>[n], <span class="dt">int</span> n))
{ ... }</code></pre>
<p>That's becoming complicated to maintain. If someone else adds a fourth specialization, you need to add a fourth inverted version of its constraint. Too bad, you still compile and calls <code class="sourceCode d">Temp</code>: <code class="sourceCode d">Temp!(<span class="dt">int</span>[])</code>. And there: error! Why? Because constraints #1a and #1b are not mutually exclusive: an <code class="sourceCode d"><span class="dt">int</span>[]</code> is also a input range. Which means that for #1b, you need to add a clause excluding arrays of <code class="sourceCode d"><span class="dt">int</span></code> and maybe modify constraint #2.</p>
<p>Ouch.</p>
<p>So, yes, constraints are wonderful, but they do have drawbacks. As a data point, this author uses them all the time, even though <a href="#templates-specializations">specializations</a> are sometimes more user-friendly: most of what I want to impose and check on my types cannot be done by specializations.</p>
<h3 id="constraints-specializations-and-static-if">Constraints, Specializations and <code>static if</code></h3>
<p>I mean, come on! Three different ways to decide if your template exists or not?</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> Specialized(T : U[], U)
{ ... }

<span class="kw">template</span> Constrained(T) <span class="kw">if</span> (<span class="kw">is</span>(T : U[], U))
{ ... }

<span class="kw">template</span> StaticIfied(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T : U[], U))
    { ... }
    <span class="kw">else</span> <span class="co">// stop compilation</span>
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;StaticIfied cannot be instantiated.&quot;</span>);
}</code></pre>
<p>What were the D designers thinking? Well, they got <a href="#templates-specializations">specializations</a> from D's cousin, C++. The two other subsystems were added a few years later, as the power of D compile-time metaprogramming became apparent and more powerful tools were needed. So, the 'modern' subsystems are constraints and <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> (<a href="#static-if">Static If</a>). Constraints are much more powerful than specializations, as anything you can test with specialization, you can test with an <code class="sourceCode d"><span class="kw">is</span></code> expression in a constraint. And <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> is wonderfully useful outside of template instantiation, so these two are well implanted in D and are there to stay.</p>
<p>What about specializations, now? First, they are quite nice to have when porting some C++ code. Second, they have a nice effect that constraints do <em>not</em> have: when more than one definition could be instantiated, priority is given to the more specialized. You saw the explanation in the previous subsection.</p>
<p>So in the end, the conclusion is a bit of <em>D Zen</em>: you are given tools, powerful tools. As these are powerful, they sometimes can do what other options in your toolbox can do also. D does not constrain (!) you, chose wisely.</p>
<h2 id="predicate-templates">Predicate Templates</h2>
<p>When you find yourself typing again and again the same <code class="sourceCode d"><span class="kw">is</span></code> expression or the same complicated constraint, it's time to abstract it into another template, a <code class="sourceCode d"><span class="dt">bool</span></code>-becoming one. If you have a look at <a href="#istype">this section</a>, you'll see a way to test if a particular piece of D code is OK (compilable) or not. Another way to obtain this is by using <code class="sourceCode d">__traits(compiles, some Code)</code>.</p>
<p>In <a href="#examples">Examples</a>, the section <a href="#mapping-filtering-and-folding-types">Type Sorcery</a> shows another example of a predicate template.</p>
<h3 id="testing-for-a-member">Testing for a member</h3>
<p>For example, if you want to test if some type can be serialized, through a <code class="sourceCode d"><span class="dt">size_t</span> serialize()</code> member function:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> isserializable;

<span class="kw">template</span> isSerializable(Type)
{
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, {
                                   Type type;
                                   <span class="dt">size_t</span> num = type.serialize;
                                  }))
        <span class="kw">enum</span> <span class="dt">bool</span> isSerializable = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">bool</span> isSerializable = <span class="kw">false</span>;
}</code></pre>
<h3 id="testing-for-operations">Testing for Operations</h3>
<p>As seen in previous sections (<a href="#example-a-concat-flatten-range">Struct Flatten</a>, <a href="#constraints-usage">Constraints Usage</a>), we are writing here a kind of compile-time interface. Any type can pass this test, as long as it has a <code class="sourceCode d">.serialize</code> member that returns a <code class="sourceCode d"><span class="dt">size_t</span></code>. Of course, you're not limited to testing member functions. Here is a template that verify some type has arithmetic operations:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> hasarithmeticoperations;

<span class="kw">template</span> hasArithmeticOperations(Type)
{
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles,
                       {
                           Type t, result;
                           result = t + t; <span class="co">// addition</span>
                           result = t - t; <span class="co">// substraction</span>
                           result = t * t; <span class="co">// multiplication</span>
                           result = t / t; <span class="co">// division</span>
                           result = +t;    <span class="co">// unary +</span>
                           result = -t;    <span class="co">// unary -</span>
                       }))
        <span class="kw">enum</span> <span class="dt">bool</span> hasArithmeticOperations = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">bool</span> hasArithmeticOperations = <span class="kw">false</span>;
}

<span class="kw">static</span> <span class="kw">assert</span>(hasArithmeticOperations!<span class="dt">int</span>);
<span class="kw">static</span> <span class="kw">assert</span>(hasArithmeticOperations!<span class="dt">double</span>);

<span class="kw">struct</span> S {}
<span class="kw">static</span> <span class="kw">assert</span>(!hasArithmeticOperations!S);</code></pre>
<p>As you can see, you can test for any type of D code, which means it's <em>much</em> more powerful than <a href="#templates-specializations">templates specializations</a> or the <code class="sourceCode d"><span class="kw">is</span></code> <a href="#the-is-expression">expression</a>.</p>
<p>You may also get a certain feel of a... <em>pattern</em> emerging from the previous two examples. All the scaffolding, the boilerplate, is the same. And we could easily template it on what operator to test, for example. It's possible to do that, but it means crafting code at compile-time. Wait until you see <a href="#string-mixins">string mixins</a> and <a href="#ctfe">CTFE</a> in <a href="#around-templates-other-compile-time-tools">Around Templates</a>.</p>
<h3 id="completing-the-flatten-range">Completing the Flatten range</h3>
<p>Let's come back to <code class="sourceCode d">Flatten</code> from section <a href="#example-a-concat-flatten-range">Struct Flatten</a>. Using concept-checking templates, we will verify the range-ness of the wrapper type and promote <code class="sourceCode d">Flatten</code> to forward range status if <code class="sourceCode d">Range</code> itself is a forward range:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.range;

<span class="kw">struct</span> Flatten(Range) <span class="kw">if</span> (isInputRange!Range)
{
    <span class="co">/* same code as before */</span>

    <span class="kw">static</span> <span class="kw">if</span> (isForwardRange!Range)
        Flatten save() @property
        {
           <span class="kw">return</span> <span class="kw">this</span>;
        }
}</code></pre>
<p>The struct is enriched in two ways: first, it cannot be instantiated on a non-range. That's good because with the code from section <a href="#example-a-concat-flatten-range">Struct Flatten</a>, you could bypass the factory function and manually create a <code class="sourceCode d">Flatten!</code><code class="sourceCode d"><span class="dt">int</span></code>, which wouldn't do. Now, you cannot. Secondly, if the wrapped range is a forward range, then <code class="sourceCode d">Flatten!Range</code> is one also. That opens up whole new algorithms to <code class="sourceCode d">Flatten</code>, for just a quite-readable little piece of code.</p>
<p>You could extend the pattern in the same way by allowing <code class="sourceCode d">Flatten</code> to be a bidirectional range, but you would need to introduce a <code class="sourceCode d">backSubRange</code> member that keeps trace of the range's back state.</p>
<h2 id="template-tuple-parameters">Template Tuple Parameters</h2>
<h3 id="definition-and-basic-properties">Definition and Basic Properties</h3>
<p>And now comes one of my favourite subjects: template tuple parameters. As seen in section <a href="#template-declarations">Declarations</a> these are declared by putting a <code class="sourceCode d">identifier...</code> at the last parameter of a template. The tuple will then absorb any type, alias or literal passed to it. For this very reason (that it can be a bunch of types interspersed with symbols), some people consider it a mongrel addition to D templates. That is true, but the ease of use and the flexibility it gives us is in my opinion well worth the cost of a little cleanliness. D template tuples have a <code class="sourceCode d">.<span class="dt">length</span></code> member (defined at compile-time, obviously), their elements can be accessed using the standard indexing syntax and they can even be sliced (the <code class="sourceCode d">$</code> symbol is aliased to the tuple length):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> dropfront;

<span class="kw">template</span> DropFront(T...)
{
    <span class="kw">static</span> <span class="kw">if</span> ( T.<span class="dt">length</span> &gt; <span class="dv">0</span>     <span class="co">// .length. At least 1 element</span>
             &amp;&amp; <span class="kw">is</span>(T[<span class="dv">0</span>] == <span class="dt">int</span>)) <span class="co">// Indexing</span>
        <span class="kw">alias</span> T[<span class="dv">1</span>..$] DropFront; <span class="co">// Slicing</span>
    <span class="kw">else</span>
        <span class="kw">alias</span> <span class="dt">void</span> DropFront;
}

<span class="kw">alias</span> DropFront!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>) Shortened;
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( Shortened[<span class="dv">0</span>] == <span class="dt">double</span>));
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( Shortened[<span class="dv">1</span>] == <span class="dt">string</span>));</code></pre>
<p>You can declare a value of type <code>tuple'. This value (called an expression tuple) also has a length, can be indexed and can be sliced. You can also pass it directly to a function if the types check with a function parameter list. If you throw it into an array, it will</code>melt' and initialize the array:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tupledemonstration;

<span class="kw">template</span> TupleDemonstration(T...)
{
    <span class="kw">alias</span> T TupleDemonstration;
}

<span class="kw">unittest</span>
{
    TupleDemonstration!(<span class="dt">string</span>, <span class="dt">int</span>, <span class="dt">double</span>) t;

    <span class="kw">assert</span>(t.<span class="dt">length</span> == <span class="dv">3</span>);
    t[<span class="dv">0</span>] = <span class="st">&quot;abc&quot;</span>;
    t[<span class="dv">1</span>] = <span class="dv">1</span>;
    t[<span class="dv">2</span>] = <span class="fl">3.14</span>;
    <span class="kw">auto</span> t2 = t[<span class="dv">1</span>..$];
    <span class="kw">assert</span>(t2[<span class="dv">0</span>] == <span class="dv">1</span>);
    <span class="kw">assert</span>(t2[<span class="dv">1</span>] == <span class="fl">3.14</span>);

    <span class="dt">void</span> foo(<span class="dt">int</span> i, <span class="dt">double</span> d) {}
    foo(t2); <span class="co">// OK.</span>

    <span class="dt">double</span>[] array = [t2]; <span class="co">// see, between [ and ]</span>
    <span class="kw">assert</span>(array == [<span class="fl">1.0</span>, <span class="fl">3.14</span>]);
}</code></pre>
<p>The simplest possible tuple is already defined in Phobos in <a href="http://dlang.org/phobos/std_typetuple.html#TypeTuple">std.typetuple.TypeTuple</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> TypeTuple(T...)
{
   <span class="kw">alias</span> T TypeTuple; <span class="co">// It just exposes the T&#39;s</span>
}

<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>, <span class="dt">double</span>) ISD;
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( TypeTuple!(ISD[<span class="dv">0</span>], ISD[<span class="dv">1</span>], ISD[<span class="dv">2</span>]) == ISD ));</code></pre>
<p>Pure template parameter tuples are auto-flattening: they do <em>not</em> nest:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> ttflatten;
<span class="kw">import</span> std.typetuple;

<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>, <span class="dt">double</span>) ISD;
<span class="kw">alias</span> TypeTuple!(ISD, ISD) ISDISD;
<span class="co">// ISDISD is *not* ((int, string, double), (int, string, double))</span>
<span class="co">// It&#39;s (int, string, double, int, string, double)</span>
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(ISDISD == TypeTuple!(<span class="dt">int</span>,<span class="dt">string</span>,<span class="dt">double</span>,<span class="dt">int</span>,<span class="dt">string</span>,<span class="dt">double</span>)));</code></pre>
<p>This is both a bug and a feature. On the negative side, that condemns us to linear structures: no trees of type tuples. And since a branching structure can give rise to a linear, that would have been strictly more powerful. On the positive side, that allow us to concatenate tuples easily (and from that, to iterate easily). If you need recursive/branching structures, you can have them by using <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> or really any kind of struct/class template: the types are not flattened there. See for example section <a href="#a-polymorphic-tree">Polymorphic Tree</a> for a fully polymorphic tree.</p>
<p>The last property tuples have is that they can be iterated over: use a <code class="sourceCode d"><span class="kw">foreach</span></code> expression, like you would for an array. With <code class="sourceCode d"><span class="kw">foreach</span></code>, you can iterate on both type tuples and expression tuples. The indexed version is also possible, but you cannot ask directly for a <code class="sourceCode d"><span class="kw">ref</span></code> access to the values (but see the example below). This iteration is done at compile-time and is in fact one of the main ways to get looping at compile-time in D.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> ttiteration;

<span class="kw">import</span> std.typetuple;

<span class="kw">unittest</span>
{
    <span class="kw">alias</span> TypeTuple!(<span class="dt">string</span>, <span class="dt">int</span>, <span class="dt">double</span>) T;
    T t;
    t[<span class="dv">0</span>] = <span class="st">&quot;abc&quot;</span>;
    t[<span class="dv">1</span>] = <span class="dv">1</span>;
    t[<span class="dv">2</span>] = <span class="fl">3.14</span>;

    <span class="dt">string</span>[T.<span class="dt">length</span>] s;

    <span class="kw">foreach</span>(index, Type; T) <span class="co">// Iteration on types.</span>
                            <span class="co">// Type is a different, er, type at each position</span>
    {
        <span class="kw">static</span> <span class="kw">if</span>(<span class="kw">is</span>(Type == <span class="dt">double</span>))
            s[index] = Type.<span class="dt">stringof</span>;
    }
    <span class="kw">assert</span>(s ==  [<span class="st">&quot;&quot;</span>, <span class="st">&quot;&quot;</span>, <span class="st">&quot;double&quot;</span>]);

    <span class="dt">void</span> bar(T)(<span class="kw">ref</span> T d) { T t; d = t;}

    <span class="kw">foreach</span>(index, value; t) <span class="co">// Iteration on values.</span>
                             <span class="co">// value has a different type at each position!</span>
    {
        bar(t[index]); <span class="co">// use t[iindex], not &#39;value&#39; to get a ref access</span>
    }

    <span class="kw">assert</span>(t[<span class="dv">0</span>] == <span class="st">&quot;&quot;</span>);
    <span class="kw">assert</span>(t[<span class="dv">1</span>] == <span class="dv">0</span>);

    <span class="kw">import</span> std.math;
    <span class="kw">assert</span>(std.math.isnan(t[<span class="dv">2</span>]));
}</code></pre>
<p>As values of this type can be created and named, they are <em>almost</em> first-class. They have two limitations, however:</p>
<ul>
<li>There is no built-in syntax for declaring a tuple. In the previous example, calling <code class="sourceCode d">T.<span class="dt">stringof</span></code> returns the string <code class="sourceCode d"><span class="st">&quot;(string, int,double)&quot;</span></code>. But you cannot write <code class="sourceCode d">(<span class="dt">string</span>, <span class="dt">int</span>, <span class="dt">double</span>) myTuple;</code> directly. Paradoxically, if you have a <code class="sourceCode d">(<span class="dt">string</span>, <span class="dt">int</span>, <span class="dt">double</span>)</code> type tuple called <code class="sourceCode d">T</code>, you <em>can</em> do <code class="sourceCode d">T myTuple;</code>.</li>
<li>These tuples cannot be returned from a function. You have to wrap them in a struct. That's what <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> offers.</li>
</ul>
<h3 id="tuple-tuple-t...-and-.tupleof"><code>Tuple</code>, <code>tuple</code>, <code>T...</code> and <code>.tupleof</code></h3>
<p>A common question from newcomers to D is the difference and definition between the different tuples found in the language and the standard library. I will try to explain:</p>
<dl>
<dt>Template tuple parameters</dt>
<dd><p>are internal to templates. They are declared with <code class="sourceCode d">T...</code> at the last position in the parameter list. They group together a list of template parameters, be they types, values or alias. Two `subtypes' are commonly used:</p>
</dd>
<dt>Type tuples</dt>
<dd><p>are template tuple parameters that hold only types.</p>
</dd>
<dt>Expression tuples</dt>
<dd><p>are tuples that hold only expressions. They are what you get when you declare a variable of type `type tuple'.</p>
</dd>
<dt>Function parameter tuples</dt>
<dd><p>You can get a function parameter type tuple from <a href="http://dlang.org/phobos/std_traits.html#ParameterTypeTuple">std.traits.ParameterTypeTuple</a>. It's exactly a type tuple as seen before. A value of this type can be declared and can be passed to a function with the same parameters.</p>
</dd>
<dt>The .tupleof property</dt>
<dd><p>is a property of aggregate types: classes and structs. It returns an expression tuple containing the members's values.</p>
</dd>
<dt>Member names tuple</dt>
<dd><p>is a tuple of strings you get by using <code class="sourceCode d">__traits(members,</code> <code class="sourceCode d">SomeType)</code>. It contains all <code class="sourceCode d">SomeType</code> members names, as strings (including the methods, constructors, aliases and such).</p>
</dd>
<dt>std.typetuple.TypeTuple</dt>
<dd><p><a href="http://dlang.org/phobos/std_typetuple.html#TypeTuple">std.typetuple.TypeTuple</a> is a pre-defined template in Phobos that's the simplest possible template holding a tuple. It's the common D way to deal with type tuples. The name is bit of a misnomer, because it's a standard template parameter tuple: it can hold types, but also values.</p>
</dd>
<dt>std.typecons.Tuple</dt>
<dd><p><a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> and <a href="http://dlang.org/phobos/std_typecons.html#tuple">std.typecons.tuple</a> are pre-defined struct/function templates in Phobos that gives a simple syntax to manipulate tuples and return them from functions.</p>
</dd>
</dl>
<h3 id="the-type-of-tuples">The Type of Tuples</h3>
<p>You can get a tuple's type by using <code class="sourceCode d"><span class="dt">typeof</span></code><code class="sourceCode d">(tuple)</code>, like any other D type. There are two limit cases:</p>
<dl>
<dt>One-element tuples.</dt>
<dd><p>There is a difference between a tuple of one element and a lone type. You cannot initialize a standard value with a 1-element tuple. You have to extract the first (and only) element before. In the same idea, the 1-element tuple has a length and can be sliced: actions that do not make sense for a standard type.</p>
</dd>
<dt>Zero-element tuples.</dt>
<dd><p>It's possible to have an empty tuple, holding zero type, not to be confused with a uninitialized n-elements tuple or the tuple holding <code class="sourceCode d"><span class="dt">void</span></code> as a type. In fact, the zero-element tuple can only have one value: its initialization value. For this reason, it's sometimes called the Unit type.<a href="#fn10" class="footnoteRef" id="fnref10"><sup>10</sup></a></p>
</dd>
</dl>
<h5 id="void-containing-tuples-and-empty-tuples">void-containing tuples and empty tuples:</h5>
<p>A type tuple may hold the <code class="sourceCode d"><span class="dt">void</span></code> type, like any other D type. It 'takes a slot' in the tuple and a tuple holding only a <code class="sourceCode d"><span class="dt">void</span></code> is <em>not</em> the empty tuple.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> emptytuple;
<span class="kw">import</span> std.typetuple;

<span class="kw">alias</span> TypeTuple!(<span class="dt">void</span>) Void;
<span class="kw">alias</span> TypeTuple!() Empty;
<span class="kw">static</span> <span class="kw">assert</span>( !<span class="kw">is</span>(Void == Empty) );

<span class="kw">static</span> <span class="kw">assert</span>(!<span class="kw">is</span>( TypeTuple!(<span class="dt">int</span>, <span class="dt">void</span>, <span class="dt">string</span>) == TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>)));</code></pre>
<h4 id="example-variadic-functions">Example: Variadic Functions</h4>
<p>Tuples are very useful to make function templates variadic (that is, accept a different number of parameters). Without restriction on the passe-in types, you will need most of the time another function template to process the arguments. A standard example for this is transforming all parameters into a <code class="sourceCode d"><span class="dt">string</span></code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> variadic;

<span class="dt">string</span> toStrings(<span class="dt">string</span> sep = <span class="st">&quot;, &quot;</span>, Args...)(Args args)
{
    <span class="kw">import</span> std.conv;
    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(index, argument; args)
    {
        result ~= to!<span class="dt">string</span>(argument);
        <span class="kw">if</span> (index != args.<span class="dt">length</span> - <span class="dv">1</span>)
            result ~= sep; <span class="co">// not for the last one</span>
    }
    <span class="kw">return</span> result;
}

<span class="kw">unittest</span>
{
    <span class="kw">assert</span>( toStrings(<span class="dv">1</span>, <span class="st">&quot;abc&quot;</span>, <span class="fl">3.14</span>, <span class="ch">&#39;a&#39;</span>, [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>])
                  == <span class="st">&quot;1, abc, 3.14, a, [1, 2, 3]&quot;</span>);
}</code></pre>
<p>If you want to restrict the number of parameters or their types, use template constraints:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="dt">int</span> howMany(Args...)(Args args)
    <span class="kw">if</span> (Args.<span class="dt">length</span> &gt; <span class="dv">1</span> &amp;&amp; Args.<span class="dt">length</span> &lt; <span class="dv">10</span>)
{
    <span class="kw">return</span> args.<span class="dt">length</span>; <span class="co">// == Args.length</span>
}</code></pre>
<p>Imagine you a have a bunch of ranges. Since they all have different types, you cannot put them in an array. And since most of them are structs, you cannot cast them to a base type, as you would for classes. So you hold them in a tuple. Then, you need to call the basic range methods on them: calling <code class="sourceCode d">popFront</code> on all of them, etc. Here is a possible way to do that:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> popallfronts;
<span class="kw">import</span> std.range, std.algorithm;
<span class="kw">import</span> areallranges;

<span class="dt">void</span> popAllFronts(Ranges...)(<span class="kw">ref</span> Ranges ranges)
    <span class="kw">if</span>(areAllRanges!Ranges)
{
    <span class="kw">foreach</span>(index, range; ranges)
        ranges[index].popFront; <span class="co">// to get a ref access</span>
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> arr1 = [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>];
    <span class="kw">auto</span> arr2 = <span class="st">&quot;Hello, World!&quot;</span>;
    <span class="kw">auto</span> arr3 = map!<span class="st">&quot;a*a&quot;</span>(arr1);

    popAllFronts(arr1, arr2, arr3);

    <span class="kw">assert</span>(arr1 == [<span class="dv">1</span>,<span class="dv">2</span>]);
    <span class="kw">assert</span>(arr2 == <span class="st">&quot;ello, World!&quot;</span>);
    <span class="kw">assert</span>(equal( arr3, [<span class="dv">1</span>,<span class="dv">4</span>]));
}</code></pre>
<p>It works for any number of ranges, that's cool. And it's checked at compile-time, you cannot pass it an <code class="sourceCode d"><span class="dt">int</span></code> discretly, hoping no one will see: it's the job of <code class="sourceCode d">areAllRanges</code> to verify that. Its code is a classical example of recursion on type tuples:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> areallranges;
<span class="kw">import</span> std.range;

<span class="kw">template</span> areAllRanges(Ranges...)
{
    <span class="kw">static</span> <span class="kw">if</span> (Ranges.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// Base case: stop.</span>
        <span class="kw">enum</span> areAllRanges = <span class="kw">true</span>;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (!isInputRange!(Ranges[<span class="dv">0</span>])) <span class="co">// Found a not-range:stop.</span>
        <span class="kw">enum</span> areAllRanges = <span class="kw">false</span>;
    <span class="kw">else</span> <span class="co">// Continue the recursion</span>
        <span class="kw">enum</span> areAllRanges = areAllRanges!(Ranges[<span class="dv">1</span>..$]);
}</code></pre>
<p>People used to languages like lisp/Scheme or Haskell will be right at home there. For the others, a little explanation might be in order:</p>
<ul>
<li>when you get a typetuple, either it's empty or it's not.
<ul>
<li>If it's empty, then all the elements it holds are ranges and we return <code class="sourceCode d"><span class="kw">true</span></code>.</li>
<li>If it's not empty, it has at least one element, which can be accessed by indexing. Let's test it: either it's a range or it's not.
<ul>
<li>If it isn't a range, the iteration stops: not all elements are ranges, we return <code class="sourceCode d"><span class="kw">false</span></code>.</li>
<li>If it's a range... we have not proved anything, and need to continue.</li>
</ul></li>
</ul></li>
</ul>
<p>The recursion is interesting: by defining an <code class="sourceCode d">areAllRanges</code> manifest constant, we will activate the <a href="#the-eponymous-trick">eponymous template</a> trick, which gets initialized to the value obtained by calling the template on a shortened tuple. With slicing, we drop the first type (it was already tested) and continue on the next one. In the end, either we exhausted the tuple (the length == 0 case) or we find a non-range.</p>
<h4 id="one-element-tuples-accepting-types-and-alias">One-Element Tuples: Accepting Types and Alias</h4>
<p>Sometimes it makes sense for a template to accept either a type parameter or an alias. For example, a template that returns a string representing its argument. In that case, since type parameter do not accept symbols as arguments and the same way round for alias, you're doomed to repeat yourself:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nameof2;

<span class="kw">template</span> nameOf(T)
{
    <span class="kw">enum</span> <span class="dt">string</span> nameOf = T.<span class="dt">stringof</span>;
}

<span class="kw">template</span> nameOf(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> <span class="dt">string</span> nameOf = a.<span class="dt">stringof</span>;
}

<span class="kw">unittest</span>
{
    <span class="kw">assert</span>(nameOf!(<span class="dt">double</span>[]) == <span class="st">&quot;double[]&quot;</span>);

    <span class="dt">int</span> i;
    <span class="kw">assert</span>(nameOf!(i) == <span class="st">&quot;i&quot;</span>);
}</code></pre>
<p>Since tuples can accept both types and alias, you can use them to simplify your code a bit:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nameof3;

<span class="kw">template</span> nameOf(T...) <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">1</span>) <span class="co">// restricted to one argument</span>
{
    <span class="kw">enum</span> <span class="dt">string</span> nameOf = T[<span class="dv">0</span>].<span class="dt">stringof</span>;
}</code></pre>
<blockquote>
<p><strong>TODO</strong> A better explanation is in order. I'm not that convinced myself.</p>
</blockquote>
<h4 id="example-inheritance-lists">Example: Inheritance Lists</h4>
<blockquote>
<p><strong>Unfinished</strong> All this section should be rewritten. The compiler is more accepting than I thought.</p>
</blockquote>
<p>Using <a href="#class-templates">class templates</a>, we might want to adjust the inheritance list at compile-time. Type tuples are a nice way to it: first define a template that alias itself to a type tuple, then have the class inherit from the template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> interfacelist;
<span class="kw">import</span> std.typetuple;

<span class="kw">interface</span> I {}
<span class="kw">interface</span> J {}
<span class="kw">interface</span> K {}
<span class="kw">interface</span> L {}

<span class="kw">class</span> BaseA {}
<span class="kw">class</span> BaseB {}

<span class="kw">template</span> Inheritance(Base) <span class="kw">if</span> (<span class="kw">is</span>(Base == <span class="kw">class</span>))
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Base : BaseA))
        <span class="kw">alias</span> TypeTuple!(Base, I, J, K) Inheritance;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Base : BaseB))
        <span class="kw">alias</span> TypeTuple!(Base, L)       Inheritance;
    <span class="kw">else</span>
        <span class="kw">alias</span> Base                      Inheritance;
}

<span class="co">// Inherits from Base</span>
<span class="kw">class</span> MyClass : Inheritance!BaseA { <span class="co">/*...*/</span> }
<span class="kw">class</span> MyOtherClass : Inheritance!BaseB { <span class="co">/*...*/</span> }</code></pre>
<p>Here I templated <code class="sourceCode d">Inheritance</code> on the base class, but you could easily template it on a global <code class="sourceCode d"><span class="kw">enum</span></code>, for example. In any case, the selection is abstracted away and the choice-making code is in one place, for you to change it easily.</p>
<blockquote>
<p><strong>TODO</strong> Here I need to rewrite the junction between the two parts of this section.</p>
</blockquote>
<p>Let's begin with something more simple: given a type and a type tuple, eliminate all occurrences of the type in the type tuple.</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> eliminate;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> Eliminate(Type, TargetTuple...)
{
    <span class="kw">static</span> <span class="kw">if</span> (TargetTuple.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// Tuple exhausted,</span>
        <span class="kw">alias</span> TargetTuple
              Eliminate;    <span class="co">// job done.</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(TargetTuple[<span class="dv">0</span>] : Type))
        <span class="kw">alias</span> Eliminate!(Type, TargetTuple[<span class="dv">1</span>..$])
              Eliminate;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(TargetTuple[<span class="dv">0</span>], Eliminate!(Type, TargetTuple[<span class="dv">1</span>..$]))
              Eliminate;
}

<span class="kw">unittest</span>
{
    <span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>,<span class="dt">double</span>,<span class="dt">int</span>,<span class="dt">string</span>) Target;
    <span class="kw">alias</span> Eliminate!(<span class="dt">int</span>, Target) NoInts;
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( NoInts == TypeTuple!(<span class="dt">double</span>, <span class="dt">string</span>) ));
}</code></pre></td></tr></table>
<p>The only difficulty is on line 13: if the first type is not a <code class="sourceCode d">Type</code>, we have to keep it and continue the recursion:</p>
<pre class="sourceCode d"><code class="sourceCode d">Eliminate!(Type,  Type0, Type1, Type2, ...)
-&gt;
Type0, Eliminate!(Type,  Type1, Type2, ...)</code></pre>
<p>We cannot juxtapose types like I just did, we have to wrap them in a template. Phobos defines <code class="sourceCode d">TypeTuple</code> in <a href="http://dlang.org/phobos/std_typetuple.html">std.typetuple</a> for that use.</p>
<p>Now that we know how to get rid of all occurrences of a type in a type tuple, we have to write a template to eliminate all duplicates. The algorithm is simple: take the first type, eliminate all occurrences of this type in the remaining type tuple. Then call the duplicate elimination anew from the resulting type tuple, while at the same time collecting the first type.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> noduplicates;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> eliminate;

<span class="kw">template</span> NoDuplicates(Types...)
{
    <span class="kw">static</span> <span class="kw">if</span> (Types.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">alias</span> Types NoDuplicates; <span class="co">// No type, nothing to do.</span>
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(
                          Types[<span class="dv">0</span>]
                        , NoDuplicates!(Eliminate!(Types[<span class="dv">0</span>], Types[<span class="dv">1</span>..$]))
                        ) NoDuplicates;
}

<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>( NoDuplicates!(<span class="dt">int</span>,<span class="dt">double</span>,<span class="dt">int</span>,<span class="dt">string</span>,<span class="dt">double</span>)
                  == TypeTuple!(<span class="dt">int</span>,<span class="dt">double</span>,<span class="dt">string</span>)));</code></pre>
<p>By the way, code to do that, also called <code class="sourceCode d">NoDuplicates</code>, is already in Phobos. It can be found in <a href="http://dlang.org/phobos/std_typetuple.html">std.typetuple</a>. I found coding it again a good exercise in type tuple manipulation. You can find a few examples of this kind of templates in <a href="#type-sorcery">Type Sorcery</a>.</p>
<p>The last piece of the puzzle is to get a given class inheritance list. The <code class="sourceCode d"><span class="kw">is</span></code> expression give us that, by way of <a href="#type-specializations">type specializations</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> superlist;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> SuperList(Class) <span class="kw">if</span> (<span class="kw">is</span>(Class == <span class="kw">class</span>))
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Class Parent == <span class="kw">super</span>))
        <span class="kw">alias</span> TypeTuple!(Parent, SuperList!Parent) SuperList;
}

<span class="co">// for Object, is(Object Parent == super)) gives an empty typetuple</span>
<span class="kw">template</span> SuperList()
{
    <span class="kw">alias</span> TypeTuple!() SuperList;
}

<span class="kw">unittest</span>
{
    <span class="kw">class</span> A {}
    <span class="kw">class</span> B : A {}
    <span class="kw">class</span> C : A {}
    <span class="kw">class</span> D : C {}

    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(SuperList!<span class="dt">Object</span> == TypeTuple!()));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(SuperList!A      == TypeTuple!(<span class="dt">Object</span>)));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(SuperList!B      == TypeTuple!(A, <span class="dt">Object</span>)));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(SuperList!D      == TypeTuple!(C, A, <span class="dt">Object</span>)));
}</code></pre>
<blockquote>
<p><strong>TODO</strong> Rewrite the end.</p>
</blockquote>
<p>Now we are good to go: given a base class, get its inheritance list with <code class="sourceCode d">SuperList</code>. Drop the base class to keep the interfaces. Stitch with the interfaces provided by <code class="sourceCode d">Inheritance</code> and call <code class="sourceCode d">NoDuplicates</code> on it. To make things clearer, I will define many aliases in the template. To keep the use of <a href="#the-eponymous-trick">the eponymous trick</a>, I will defer the aliasing in another template.</p>
<blockquote>
<p><strong>TODO</strong> This is not needed anymore. As of DMD 2.060, the eponymous trick works even with internal members defined.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> checkedinheritance;
<span class="kw">import</span> superlist;
<span class="kw">import</span> interfacelist;

<span class="kw">template</span> CheckedInheritance(Base)
{
    <span class="kw">alias</span> CheckedImpl!(Base).Result CheckedInheritance;
}

<span class="kw">template</span> CheckedImpl(Base)
{
    <span class="co">/* Rewrite the</span>
<span class="co">}</span>

<span class="co">// It works!</span>
<span class="co">class NoError : CheckedInheritance!(MyClass) { /*...*/</span> }</code></pre>
<h2 id="operator-overloading">Operator Overloading</h2>
<p>D allows users to redefine some operators to enhance readability in code. And guess what? Operator overloading is based on (member) templates. They are described  in the docs.</p>
<h3 id="syntax-6">Syntax</h3>
<p>The following sections give you the operators that you can overload and which template members you must define in your custom type. <code>u</code> is a value of type <code>U</code> for which you want to define operators. <code>v</code> is a value of type <code>V</code> with which <code>u</code> will interact. <code>V</code> can be the same as <code>U</code> or a different type altogether.</p>
<p><em>op</em> is one of the 'concerned' operators introduced with each section.</p>
<h4 id="unary-operations">Unary Operations</h4>
<p>Concerned operators: <code>+</code>, <code>-</code>, <code>++</code>, <code>--</code>, <code>*</code> and <code>~</code>.</p>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><em>op</em><code>u</code></td>
<td align="left"><code>opUnary(string s)() if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="even">
<td align="left"><em>op</em><code>u[i0]</code></td>
<td align="left"><code>opIndexUnary(string s)(size_t i0) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="odd">
<td align="left"><em>op</em><code>u[i0, i1]</code></td>
<td align="left"><code>opIndexUnary(string s)(size_t i0,size_t i1) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="even">
<td align="left"><em>op</em><code>u[i0, i1, in]</code></td>
<td align="left"><code>opIndexUnary(string s)(size_t i0, ...) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="odd">
<td align="left"><em>op</em><code>u[i..j]</code></td>
<td align="left"><code>opSliceUnary(string s)(size_t i, size_t j) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="even">
<td align="left"><em>op</em><code>u[]</code></td>
<td align="left"><code>opSliceUnary(string s)() if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
</tbody>
</table>
<h4 id="binary-operations">Binary Operations</h4>
<p>Concerned operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>^^</code>, <code>~</code>, <code class="sourceCode d"><span class="kw">in</span></code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code> and <code>&gt;&gt;&gt;</code>.</p>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>u</code> <em>op</em> <code>v</code></td>
<td align="left"><code>opBinary(string s, V)(V v) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="even">
<td align="left"><code>v</code> <em>op</em> <code>u</code></td>
<td align="left"><code>opBinaryRight(string s, V)(V v) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
</tbody>
</table>
<h4 id="assignement">Assignement</h4>
<p>Concerned operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>^^</code>, <code>~</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code> and <code>&gt;&gt;&gt;</code> (no <code class="sourceCode d"><span class="kw">in</span></code>).</p>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>u</code> <em>op</em> <code>= v</code></td>
<td align="left"><code>opOpAssign(string s, V)(V v) if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
</tbody>
</table>
<h4 id="index-assignement">Index Assignement</h4>
<p>Concerned operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>^^</code>, <code>~</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code> and <code>&gt;&gt;&gt;</code> (no <code class="sourceCode d"><span class="kw">in</span></code>).</p>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>u[i0, i1, in]</code> <em>op</em> <code>= v</code></td>
<td align="left"><code>opIndexOpAssign(string s, V)(V v, size_t i0, ...)</code></td>
</tr>
<tr class="even">
<td align="left"></td>
<td align="left"><code>if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
</tbody>
</table>
<h4 id="slice-assignement">Slice Assignement</h4>
<p>Concerned operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>^^</code>, <code>~</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code> and <code>&gt;&gt;&gt;</code> (no <code class="sourceCode d"><span class="kw">in</span></code>).</p>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>u[i..j]</code> <em>op</em> <code>= v</code></td>
<td align="left"><code>opSliceOpAssign(string s, V)(V v, size_t i, size_t j)</code></td>
</tr>
<tr class="even">
<td align="left"></td>
<td align="left"><code>if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
<tr class="odd">
<td align="left"><code>u[]</code> <em>op</em> <code>= v</code></td>
<td align="left"><code>opSliceOpAssign(string s, V)(V v)</code></td>
</tr>
<tr class="even">
<td align="left"></td>
<td align="left"><code>if (s == &quot;</code><em>op</em><code>&quot;)</code></td>
</tr>
</tbody>
</table>
<h4 id="cast-operations">Cast Operations</h4>
<table>
<thead>
<tr class="header">
<th align="left">Operation</th>
<th align="left">Member template to define</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>cast(T)u</code></td>
<td align="left"><code>T opCast(T)()</code></td>
</tr>
</tbody>
</table>
<p>Many other operators can be overloaded in D, but do not demand templates.</p>
<h4 id="example-arithmetic-operators">Example: Arithmetic Operators</h4>
<blockquote>
<p><strong>TODO</strong> Tell somewhere that this is possible:</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d">Foo opBinary(<span class="dt">string</span> op:<span class="st">&quot;+&quot;</span>)(...) { ... }</code></pre>
<p>The idea behind this strange way to overload operators is to allow you to redefine many operators at once with only one method. For example, take this struct wrapping a number:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">struct</span> Number(T) <span class="kw">if</span> (isNumeric!T)
{
    T num;
}</code></pre>
<p>To give it the four basic arithmetic operators with another <code class="sourceCode d">Number</code> and another <code class="sourceCode d">T</code>, you define <code class="sourceCode d">opBinary</code> for <code class="sourceCode d">+</code>, <code class="sourceCode d">-</code>, <code class="sourceCode d">*</code> and <code class="sourceCode d">/</code>. This will activate operations were <code class="sourceCode d">Number</code> is on the left. In case it's on the right, you have to define <code class="sourceCode d">opBinaryRight</code>. Since these overloadings tend to use string mixins, I'll use them even though they are introduced only on section <a href="#string-mixins">String Mixins</a>. The basic idea is: string mixins paste code (given as a compile-time string) where they are put.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> number;
<span class="kw">import</span> std.traits;

<span class="kw">struct</span> Number(T) <span class="kw">if</span> (isNumeric!T)
{
    T num;

    <span class="kw">auto</span> opBinary(<span class="dt">string</span> op, U)(U u)
         <span class="kw">if</span> ((op == <span class="st">&quot;+&quot;</span> || op == <span class="st">&quot;-&quot;</span> || op == <span class="st">&quot;*&quot;</span> || op == <span class="st">&quot;/&quot;</span>)
         &amp;&amp; ((isNumeric!U) || <span class="kw">is</span>(U u == Number!V, V)))
    {
 <span class="kw">mixin</span>(<span class="st">&quot;alias typeof(a&quot;</span> ~ op ~ <span class="st">&quot;b) Result;</span>
<span class="st">        static if (isNumeric!U)</span>
<span class="st">            return Number!Result(a&quot;</span>~op~<span class="st">&quot;b);</span>
<span class="st">        else</span>
<span class="st">            return Number!Result(a&quot;</span>~op~<span class="st">&quot;b.num);&quot;</span>);
    }
}</code></pre>
<p><code class="sourceCode d">op</code> being a template parameter, it's usable to do compile-time constant folding: in this case the concatenation of strings to generate D code. The way the code is written, <code class="sourceCode d">Number</code>s respect the global D promotion rules. A <code class="sourceCode d">Number!<span class="dt">int</span></code> plus a <code class="sourceCode d">Number!<span class="dt">double</span></code> returns a <code class="sourceCode d">Number!<span class="dt">double</span></code>.</p>
<h4 id="special-case-in">Special Case: in</h4>
<blockquote>
<p><strong>Unfinished</strong></p>
</blockquote>
<h4 id="special-case-cast">Special Case: cast</h4>
<blockquote>
<p><strong>Unfinished</strong></p>
</blockquote>
<h2 id="mixin-templates">Mixin Templates</h2>
<p>Up to now, <em>all</em> the templates we have seen are instantiated in the same scope than their declaration. Mixin templates have a different behaviour: the code they hold is placed upon instantiation <em>right at the call site</em>. They are thus used in a completely different way than other templates.</p>
<h3 id="syntax-7">Syntax</h3>
<p>To distinguish standard templates from mixin templates, the latter have slightly different syntax. Here is how they are declared and called:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/* Declaration */</span>
<span class="kw">mixin</span> <span class="kw">template</span> NewFunctionality(T,U) { ... }


<span class="co">/* Instantiation */</span>
<span class="kw">class</span> MyClass(T,U,V)
{
    <span class="kw">mixin</span> NewFunctionality!(U,V);

    ...
}</code></pre>
<p>As you can see, you put <code class="sourceCode d"><span class="kw">mixin</span></code> before the declaration and <code class="sourceCode d"><span class="kw">mixin</span></code> before the instantiation call. All other templates niceties (constraints, default values, ...) are still there for your perusal. Symbols lookup is done in the local scope and the resulting code is included where the call was made, therefore injecting new functionality.</p>
<p>As far as I know, there is no special syntax for function, class and struct templates to be mixin templates. You will have to wrap them in a standard <code class="sourceCode d"><span class="kw">template</span></code> declaration. In the same idea, there is no notion of eponymous trick with mixin templates: there is no question of how to give access to the template's content, since the template is cracked open for you and its very content put in your code.</p>
<blockquote>
<p><strong>TODO</strong> Test for mixin T foo(T)(T t) { return t;}</p>
</blockquote>
<p>By the way, you <em>cannot</em> mix a standard template in. It used to be the case, but it's not possible anymore. Now mixin templates and non-mixin ones are strictly separated cousins.</p>
<h3 id="mixing-code-in">Mixing Code In</h3>
<p>What good are these cousins of the templates we've seen so far? They give you a nice way to place parameterized implementation inside a class or a struct. Once more, templates are a way to reduce boilerplate code. If some piece of code appears in different places in your code (for example, in structs, where there is no inheritance to avoid code duplication), you should look for a way to put it in a mixin template.</p>
<p>Also, you can put small functionalities in mixin templates, giving client code access to them to chose how they want to build their types.</p>
<p>Note that the code you place inside a mixin template doesn't have to make sense by itself (it can refer to <code class="sourceCode d"><span class="kw">this</span></code> or any not-yet-defined symbols). It just has to be syntactically correct D code.</p>
<p>For example, remember the operator overloading code we saw in section <a href="#operator-overloading">Operator Overloading</a>? Here is a mixin containing concatenating functionality:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> mixinconcatenate;
<span class="kw">import</span> std.typecons;

<span class="kw">mixin</span> <span class="kw">template</span> Concatenate()
{
    Tuple!(<span class="dt">typeof</span>(<span class="kw">this</span>), U) opBinary(<span class="dt">string</span> op, U)(U u)
    <span class="kw">if</span> (op == <span class="st">&quot;~&quot;</span>)
    {
        <span class="kw">return</span> tuple(<span class="kw">this</span>, u);
    }
}</code></pre>
<p>As you can see, it uses <code class="sourceCode d"><span class="kw">this</span></code>, even though there is no struct or class in sight. It's used like this, to give concatenation (as tuples) ability to a struct:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingmixinconcatenate;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> mixinconcatenate;

<span class="kw">struct</span> S
{
    <span class="kw">mixin</span> Concatenate;
}

<span class="kw">unittest</span>
{
    S s,t;
    <span class="kw">auto</span> result = s ~ t;
    <span class="kw">assert</span>(result == tuple(s,t));
}</code></pre>
<p>The idea to take back home is: the concatenation code is written once. It is then an offered functionality for any client scope (type) that want it. It could easily have been arithmetic operations, <code class="sourceCode d"><span class="kw">cast</span></code> operations or new methods like <code class="sourceCode d">log</code>, <code class="sourceCode d">register</code>, new members or whatever else. Build you own set of mixins and use them freely. And remember they are not limited to classes and structs: you can also use them in functions, module scopes, other templates...</p>
<blockquote>
<p><strong>Limitations.</strong> Mixin templates inject code at the local scope. They cannot add an <code class="sourceCode d"><span class="kw">invariant</span></code> clause in a class, or <code class="sourceCode d"><span class="kw">in</span></code>/<code class="sourceCode d"><span class="kw">out</span></code> clauses in a function. They can be injected into an <code class="sourceCode d"><span class="kw">invariant</span></code>/<code class="sourceCode d"><span class="kw">in</span></code>/<code class="sourceCode d"><span class="kw">out</span></code> clause.</p>
</blockquote>
<blockquote>
<p><strong>TODO</strong> Some explanation on <code>mixin templateName name;</code>, to allow mixing of more than one template. See <a href="http://dlang.org/template-mixin.html#MixinIdentifier">http://dlang.org/template-mixin.html#MixinIdentifier</a>.</p>
</blockquote>
<h3 id="mixin-example-subscriber-and-stack">Mixin Example: Subscriber and Stack</h3>
<p>This example comes from Bjorn Lietz-Spendig, who was kind enough to allow me to use it there. Thanks Bjorn!</p>
<p>We will define two mixin templates <code class="sourceCode d">PublisherMixin</code> and <code class="sourceCode d">StackMixin</code>, the first one implementing a subscription/unsubscription engine, the second providing the standard stack operations (<code class="sourceCode d">push</code>, <code class="sourceCode d">pop</code>,...). I'd like you to notice two important things here:</p>
<ul>
<li>D allowing local imports, <code class="sourceCode d">PublisherMixin</code> imports the machinery necessary for it to function: <a href="http://dlang.org/phobos/std_functional.html#toDelegate">std.functional.toDelegate</a> and <a href="http://dlang.org/phobos/stdio.html">std.stdio</a>. Local imports really allow D template mixins to provide a nicely wrapped functionality as a coherent whole.</li>
<li><code class="sourceCode d"><span class="kw">alias</span> <span class="dt">typeof</span>(<span class="kw">this</span>)</code> (here called <code class="sourceCode d">Me</code>) is also a nice feature to remember: the mixin will 'look around', get the local <code class="sourceCode d"><span class="kw">this</span></code> type and can then provide generic ready-to-be-used code.</li>
</ul>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> publisher;

<span class="kw">public</span> <span class="kw">mixin</span> <span class="kw">template</span> PublisherMixin()
{
    <span class="kw">import</span> std.functional : toDelegate;
    <span class="kw">import</span> std.stdio;

    <span class="kw">alias</span> <span class="dt">void</span> <span class="kw">delegate</span>(<span class="dt">Object</span> sender, <span class="dt">string</span> event) CallBack;
    <span class="kw">alias</span> <span class="dt">void</span> <span class="kw">function</span>(<span class="dt">Object</span> sender, <span class="dt">string</span> event) CallBackFun;


    <span class="dt">bool</span>[CallBack] callBacks;  <span class="co">// int[0][CallBack] may be even smaller</span>

    <span class="co">//Register subscriber</span>
    <span class="dt">void</span> register(CallBack callBack)
    {
    <span class="co">// Ensure subscriber is not yet registered.</span>
        <span class="kw">if</span> (callBack <span class="kw">in</span> callBacks)
            writeln(<span class="st">&quot;Subscriber is already registered.&quot;</span>);
        <span class="kw">else</span>
            callBacks[callBack] = <span class="kw">true</span>; <span class="co">//from;</span>
    }

<span class="co">// Register Subscriber via function ptr.</span>
    <span class="dt">void</span> register(CallBackFun callBackFun)
    {
        register( toDelegate(callBackFun) );
    }

    <span class="co">// Remove Subscriber</span>
    <span class="dt">void</span> unRegister(CallBack callBack)
    {
        <span class="kw">if</span> (callBack <span class="kw">in</span> callBacks)
            callBacks.remove(callBack);
        <span class="kw">else</span>
            writeln(<span class="st">&quot;Trying to remove an unknown callback.&quot;</span>);
    }

    <span class="co">// Remove Subscriber via function ptr.</span>
    <span class="dt">void</span> unRegister(CallBackFun callBackFun)
    {
        unRegister(toDelegate(callBackFun));
    }

    <span class="co">// Notify ALL Subscribers</span>
    <span class="dt">void</span> notify(<span class="dt">Object</span> from, <span class="dt">string</span> evt)
    {
        <span class="kw">foreach</span> ( CallBack cb, <span class="dt">bool</span> origin ; callBacks )
        {
            cb( from, evt );
        }
    }
}

<span class="kw">mixin</span> <span class="kw">template</span> StackMixin()
{
    <span class="co">// get parent type</span>
    <span class="kw">alias</span> <span class="dt">typeof</span>(<span class="kw">this</span>) Me;
    <span class="kw">static</span> Me[] stack;

<span class="kw">protected</span>:

    @property <span class="dt">bool</span> empty()  { <span class="kw">return</span> stack.<span class="dt">length</span> == <span class="dv">0</span>;  }
    @property <span class="dt">size_t</span> count()   { <span class="kw">return</span> stack.<span class="dt">length</span>; }

    <span class="dt">void</span> push(Me element)
    {
        stack ~= element;
    }

    Me pop()
    {
        Me el = peek();
        stack.<span class="dt">length</span> -= <span class="dv">1</span>;
        <span class="kw">return</span> el;
    }

    Me peek()
    {
        <span class="kw">if</span> ( stack.<span class="dt">length</span> == <span class="dv">0</span> )
            <span class="kw">throw</span> <span class="kw">new</span> <span class="dt">Exception</span>(<span class="st">&quot;peek on an empty statck.&quot;</span>);

        Me el = stack[stack.<span class="dt">length</span>-<span class="dv">1</span>];
        <span class="kw">return</span> el;
    }
}</code></pre>
<p>Now that the mixins are defined, we can inject them into any structure with a defined <code class="sourceCode d"><span class="kw">this</span></code>. Here we will use classes to show that mixins are inherited. Let's get some <code class="sourceCode d">Friend</code>s:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> friends;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> publisher;

<span class="kw">class</span> FriendStack
{
    <span class="kw">private</span> <span class="dt">string</span> name;
    <span class="kw">private</span> <span class="dt">int</span> age;

    <span class="co">// Our Mixins</span>
    <span class="kw">mixin</span> StackMixin;
    <span class="kw">mixin</span> PublisherMixin;

    <span class="dt">void</span> pushFriend(<span class="dt">string</span> name, <span class="dt">int</span> age)
    {
        <span class="co">// Create new instance for the Stack.</span>
        <span class="kw">auto</span> person = <span class="kw">new</span> FriendStack();
        person.name = name;
        person.age = age;

        push(person);

        <span class="co">// Notify all subscribers</span>
        notify(person, <span class="st">&quot;Push&quot;</span>);
    }

    <span class="co">//Pop</span>
    <span class="dt">void</span> popFriend()
    {
        <span class="kw">auto</span> person = pop();
        notify( person, <span class="st">&quot;Pop&quot;</span>);
    }

    <span class="co">// Subscriber method</span>
    <span class="dt">void</span> inHouseInfo(<span class="dt">Object</span> sender, <span class="dt">string</span> msg)
    {
        <span class="kw">auto</span> p = <span class="kw">cast</span>(FriendStack)sender;
        writefln(<span class="st">&quot;Subscriber: in House , Name: %s, Age: %s, Message: %s \n&quot;</span>,
                 p.name, p.age, msg);
    }
}

<span class="kw">class</span> ExtFriendStack : FriendStack <span class="co">// our VIPs</span>
{
    <span class="kw">private</span> <span class="dt">bool</span> isDeveloper;

    <span class="co">// Push</span>
    <span class="dt">void</span> pushFriend(<span class="dt">string</span> name, <span class="dt">int</span> age, <span class="dt">bool</span> D)
    {
        <span class="co">// Create new instance for the Stack.</span>
        <span class="kw">auto</span> xperson = <span class="kw">new</span> ExtFriendStack();
        xperson.name = name;
        xperson.age = age;
        xperson.isDeveloper = D;

        push(xperson);

        <span class="co">// Notify all subscribers</span>
        notify(xperson, <span class="st">&quot;Push&quot;</span>);
    }
}

<span class="co">/**</span>
<span class="co"> *</span>
<span class="co"> *  FRIENDSTACK Subscriber functions - Used by FriendStack AND ExtFriendStack.</span>
<span class="co"> */</span>
<span class="dt">void</span> twitter(<span class="dt">Object</span> sender, <span class="dt">string</span> msg)
{
    <span class="kw">auto</span> p = <span class="kw">cast</span>(FriendStack)sender;
    writefln(<span class="st">&quot;Subscriber: Twitter, Name: %s, Age: %s, Message: %s \n&quot;</span>,
             p.name, p.age, msg);
}

<span class="dt">void</span> reddit(<span class="dt">Object</span> sender, <span class="dt">string</span> msg)
{
    <span class="kw">auto</span> p = <span class="kw">cast</span>(FriendStack)sender;
    writefln(<span class="st">&quot;Subscriber: Reddit, Name: %s, Age: %s, Message: %s \n&quot;</span>,
             p.name, p.age, msg);
}

<span class="dt">void</span> mail(<span class="dt">Object</span> sender, <span class="dt">string</span> msg)
{
    <span class="kw">auto</span> p = <span class="kw">cast</span>(FriendStack)sender;
    writefln(<span class="st">&quot;Subscriber: eMail, Name: %s, Age: %s, Message: %s \n&quot;</span>,
             p.name, p.age, msg);
}

<span class="co">/**</span>
<span class="co"> *</span>
<span class="co"> *  EXTENDED FRIENDSTACK Subscriber functions</span>
<span class="co"> *  contains additional --isDeveloper-- information.</span>
<span class="co"> */</span>
<span class="dt">void</span> blog(<span class="dt">Object</span> sender, <span class="dt">string</span> msg)
{
    <span class="kw">if</span> ( <span class="kw">cast</span>(ExtFriendStack)sender )
    {
        <span class="kw">auto</span> p = <span class="kw">cast</span>(ExtFriendStack)sender;
        writefln(<span class="st">&quot;Subscriber: Blog, Name: %s, Age: %s, Is Developer ?: %s, Message: %s \n&quot;</span>,
                 p.name, p.age, p.isDeveloper, msg);
    }
    <span class="kw">else</span>
    {
        writeln(<span class="st">&quot;----- Blog is for VIPs only ------ Message rooted to email&quot;</span>);
        mail(sender, msg);

        <span class="co">// Downcast is also possible</span>
        <span class="co">//auto p = cast(FriendStack)sender;</span>
        <span class="co">//writefln(&quot;Subscriber: Blog, Name: %s, Age:  %s, Message: %s \n&quot;,</span>
        <span class="co">//         p.name, p.age, msg);</span>
    }
}</code></pre>
<p>And now we can use the stacks to our heart's content and get some friends:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingfriends;
<span class="kw">import</span> friends;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> p = <span class="kw">new</span> FriendStack();
    <span class="kw">auto</span> p2 = <span class="kw">new</span> ExtFriendStack();

    <span class="co">// Register  some subscribers.</span>
    p.register(  &amp;twitter );
    p2.register( &amp;twitter );
    p2.register( &amp;blog );
    p2.register( &amp;blog );

    <span class="co">// Push and Pop</span>
    p.pushFriend( <span class="st">&quot;Alex&quot;</span>, <span class="dv">19</span> );
    p.pushFriend( <span class="st">&quot;Tommy&quot;</span>, <span class="dv">55</span>);
    p2.pushFriend( <span class="st">&quot;Hans&quot;</span>, <span class="dv">42</span>, <span class="kw">false</span>);
    p2.pushFriend( <span class="st">&quot;Walt&quot;</span>, <span class="dv">101</span>, <span class="kw">true</span>);

    p.popFriend();
    p2.popFriend();
    p2.popFriend();

    p.unRegister( &amp;twitter );
    p2.unRegister( &amp;twitter );
    p.register( &amp;blog );
    p.pushFriend( <span class="st">&quot;Alexej&quot;</span>, <span class="dv">33</span> );
}</code></pre>
<p>If you run the previous code, you'll see that a <code class="sourceCode d">DeveloperStack</code> inherits the mixins from <code class="sourceCode d">PersonStack</code>: it's both a stack and a publisher. Thanks to <code class="sourceCode d"><span class="kw">alias</span> <span class="dt">typeof</span>(<span class="kw">this</span>)</code> defined in <code class="sourceCode d">StackMixin</code>, <code class="sourceCode d">ExtFriendStack</code> can contain additional information.</p>
<h2 id="opdispatch">opDispatch</h2>
<h3 id="syntax-8">Syntax</h3>
<p><code class="sourceCode d">opDispatch</code> is a sort of operator overloading (it's in the same place in the ) that deals with members calls (methods or value members). Its definition is the same as an operator:</p>
<pre class="sourceCode d"><code class="sourceCode d">... opDispatch(<span class="dt">string</span> name)()
... opDispatch(<span class="dt">string</span> name, Arg)(Arg arg)
... opDispatch(<span class="dt">string</span> name, Args...)(Args args)</code></pre>
<p>The usual template constraints can be used: constraints on <code class="sourceCode d">name</code>, constraints on the arguments.</p>
<p>When a type has an <code class="sourceCode d">opDispatch</code> method and a member call is done without finding a defined member, the call is dispatched to <code class="sourceCode d">opDispatch</code> with the invoked name as a string.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> dispatcher;
<span class="kw">import</span> std.typetuple;

<span class="kw">struct</span> Dispatcher
{
    <span class="dt">int</span> foo(<span class="dt">int</span> i) { <span class="kw">return</span> i*i;}
    <span class="dt">string</span> opDispatch(<span class="dt">string</span> name, T...)(T t)
    {
        <span class="kw">return</span> <span class="st">&quot;Dispatch activated: &quot;</span> ~ name ~ <span class="st">&quot;:&quot;</span> ~ TypeTuple!(T).<span class="dt">stringof</span>;
    }
}

<span class="dt">void</span> main()
{
    Dispatcher d;

    <span class="kw">auto</span> i = d.foo(<span class="dv">1</span>); <span class="co">// compiler finds foo, calls foo.</span>
    <span class="kw">auto</span> s1 = d.register(<span class="st">&quot;abc&quot;</span>); <span class="co">// no register member -&gt; opDispatch activated;</span>
    <span class="kw">assert</span>(s1 == <span class="st">&quot;Dispatch activated: register:(string)&quot;</span>);

    <span class="kw">auto</span> s2 = d.empty; <span class="co">// no empty member, no argument.</span>
    <span class="kw">assert</span>(s2 == <span class="st">&quot;Dispatch activated: empty:()&quot;</span>);
}</code></pre>
<p>Once <code class="sourceCode d">opDispatch</code> has the name called and the arguments, it's up to you to decide what to do: calling free functions, calling other methods or using the compile-time string to generate new code (see section <a href="#string-mixins">String Mixins</a>).</p>
<p>Since string mixins really go hand in hand with <code class="sourceCode d">opDispatch</code>, I'll use them even though I haven't introduced them right now. The executive summary is: they paste D code (given as a compile-time string) where they are called. There.</p>
<h3 id="getters-and-setters">Getters and Setters</h3>
<p>For example, suppose you have a bunch of members, all private and want client code to access them through good ol' <code class="sourceCode d">setXXX/getXXX</code> methods. Only, you do not want to write all these methods by yourself. You lucky you, <code class="sourceCode d">opDispatch</code> can help you.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> getset;

<span class="kw">class</span> GetSet
{
    <span class="kw">private</span> <span class="dt">int</span> i;
    <span class="kw">private</span> <span class="dt">int</span> j;
    <span class="kw">private</span> <span class="dt">double</span> d;
    <span class="kw">private</span> <span class="dt">string</span> theString;

    <span class="kw">auto</span> opDispatch(<span class="dt">string</span> name)() <span class="co">// no arg version -&gt; getter</span>
    <span class="kw">if</span> (name.<span class="dt">length</span> &gt; <span class="dv">3</span> &amp;&amp; name[<span class="dv">0</span>..<span class="dv">3</span>] == <span class="st">&quot;get&quot;</span>)
    {
        <span class="kw">enum</span> <span class="dt">string</span> member = name[<span class="dv">3</span>..$]; <span class="co">// &quot;getXXX&quot; -&gt; &quot;XXX&quot;</span>
        <span class="co">// We test if &quot;XXX&quot; exists here: ie if is(typeof(this.XXX)) is true</span>
        <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles,
                            <span class="kw">mixin</span>(<span class="st">&quot;is(typeof(this.&quot;</span> ~ member ~ <span class="st">&quot;))&quot;</span>)))
        <span class="kw">mixin</span>(<span class="st">&quot;return &quot;</span> ~ member ~ <span class="st">&quot;;&quot;</span>);
        <span class="kw">else</span>
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;GetSet Error: no member called &quot;</span> ~ member);
    }

    <span class="kw">auto</span> opDispatch(<span class="dt">string</span> name, Arg)(Arg arg) <span class="co">// setter</span>
        <span class="kw">if</span> (name.<span class="dt">length</span> &gt; <span class="dv">3</span> &amp;&amp; name[<span class="dv">0</span>..<span class="dv">3</span>] == <span class="st">&quot;set&quot;</span>)
    {
        <span class="kw">enum</span> <span class="dt">string</span> member = name[<span class="dv">3</span>..$]; <span class="co">// &quot;setXXX&quot; -&gt; &quot;XXX&quot;</span>
        <span class="co">// We test if &quot;member&quot; can be assigned to. this.member = Arg.init</span>
          <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, <span class="kw">mixin</span>(<span class="st">&quot;{&quot;</span> ~ member ~ <span class="st">&quot; = Arg.init;}&quot;</span>)))
          {
              <span class="kw">mixin</span>(member ~ <span class="st">&quot; = arg;&quot;</span>);
              <span class="kw">mixin</span>(<span class="st">&quot;return &quot;</span> ~ member ~ <span class="st">&quot;;&quot;</span>);
          }
          <span class="kw">else</span>
              <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;GetSet Error: no member called&quot;</span> ~ member);
    }
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> gs = <span class="kw">new</span> GetSet();
    gs.seti(<span class="dv">3</span>);
    <span class="kw">auto</span> i = gs.geti;
    <span class="kw">assert</span>(i == <span class="dv">3</span>);

    gs.settheString(<span class="st">&quot;abc&quot;</span>);
    <span class="kw">assert</span>(gs.gettheString == <span class="st">&quot;abc&quot;</span>); <span class="co">// &quot;abc&quot;</span>
}</code></pre>
<p>Nifty, eh? This could be a bit better by dealing with the capitalization of the first letter: <code class="sourceCode d">getTheString</code>, but this is good enough for now. Even better, you could put this code in a mixin template to give this get/set capacity to any struct or class (see section <a href="#mixin-templates">Mixin Templates</a>).</p>
<h2 id="wrapping-and-subtyping-expanding-types">Wrapping and Subtyping: Expanding Types</h2>
<h3 id="wrapper-templates">Wrapper Templates</h3>
<blockquote>
<p><strong>Unfinished</strong> The idea is to put some functionality inside before (and possibly, after) the dispatching code.</p>
</blockquote>
<p>We've seen how to inject code with <a href="#mixin-templates">mixin templates</a>) or use template class inheritance to modify you classes' code (<a href="#adding-functionalities-through-inheritance">Adding Functionalities Through Inheritance</a>). We've also seen how you can define a wrapper struct around a range to expose a new iteration scheme for its element (<a href="#example-a-concat-flatten-range">Struct Flatten</a>). All these idioms are way to modify pre-existing code.</p>
<p>But what you want to put a logging functionality around a predefined struct, so that any method call is logged? For class, you can inherit from the class and defined a subclass with new, modified, methods. But you have to do that `by hand', so to speak. And for a struct, you're out of luck.</p>
<p>But, templates can come to the rescue, with a bit of <code class="sourceCode d">opDispatch</code> magic.</p>
<blockquote>
<p><strong>TODO</strong> Finish this.</p>
</blockquote>
<ul>
<li>put Type wrapped into a Logger struct.</li>
<li>get Type.tupleof</li>
<li>call typeof() on this.</li>
<li>opDispatch Test if wrapped.foo() is legal.</li>
</ul>
<h3 id="alias-this-transparent-types">alias this: Transparent Types</h3>
<p>We will play a little bit with <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code>. Let us define a small wrapper type:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> transp;

<span class="kw">struct</span> Transparent(T)
{
    T value;
    <span class="kw">alias</span> value <span class="kw">this</span>;
}

<span class="co">// factory function</span>
Transparent!T transparent(T)(T t)
{
    <span class="kw">return</span> Transparent!T(t);
}</code></pre>
<p>This defines <code class="sourceCode d">Transparent</code>, a small struct holding a lone value of type <code class="sourceCode d">T</code>. If a <code class="sourceCode d">Transparent!T</code> is asked to do something for which it has no method nor the correct type (that is to say, almost every action you can imagine!), <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code> activates and uses <code class="sourceCode d">value</code> in lieu of <code class="sourceCode d">Transparent!T</code>. This gives us a very transparent wrapper:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingtransparent;
<span class="kw">import</span> transp;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> i = transparent(<span class="dv">10</span>);
    <span class="kw">assert</span>(i == <span class="dv">10</span>); <span class="co">// equality testing</span>

    i = <span class="dv">1</span>; <span class="co">// Assignment from an int</span>

    ++i; <span class="co">// ++ acts on i.value</span>
    <span class="kw">assert</span>(i == <span class="dv">2</span>);

    <span class="co">// int-accepting function</span>
    <span class="dt">int</span> foo(<span class="dt">int</span> ii) { <span class="kw">return</span> ii+<span class="dv">1</span>;}

    <span class="kw">assert</span>(foo(i) == <span class="dv">3</span>); <span class="co">// function calls</span>

    <span class="dt">int</span> trueInt = i; <span class="co">// transmits its value</span>

    <span class="kw">assert</span>(trueInt == <span class="dv">2</span>);
    <span class="kw">assert</span>(i == <span class="dv">2</span>);
    <span class="kw">assert</span>(i == trueInt);

    <span class="co">// Successive calls all collapse into one Transparent.</span>
    i = transparent(transparent(i));
}</code></pre>
<p>As you can see, <code class="sourceCode d">Transparent</code> behaves very gracefully: in almost all circumstances where an <code class="sourceCode d"><span class="dt">int</span></code> could fit, <code class="sourceCode d">Tranparent!</code><code class="sourceCode d"><span class="dt">int</span></code> will act as a real <code class="sourceCode d"><span class="dt">int</span></code>. Of course, its type is still OK:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">assert</span>(<span class="kw">is</span>(<span class="dt">typeof</span>(i) == Transparent!<span class="dt">int</span>));</code></pre>
<p>Another wrapper can be added:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> transp2;
<span class="kw">import</span> transp;

<span class="kw">struct</span> Thin(T)
{
    T value;
    <span class="kw">alias</span> value <span class="kw">this</span>;
}

Thin!T thin(T)(T t)
{
    <span class="kw">return</span> Thin!T(t);
}

<span class="kw">unittest</span>
{
    <span class="kw">auto</span> i = transparent(<span class="dv">10</span>);
    <span class="kw">auto</span> t = thin(i); <span class="co">// Works.</span>
    <span class="kw">assert</span>(t == <span class="dv">10</span>); <span class="co">// Yep, value was transmitted correctly.</span>

    <span class="kw">assert</span>(<span class="kw">is</span>(<span class="dt">typeof</span>(t) == Thin!(Transparent!<span class="dt">int</span>)));
}</code></pre>
<p>What's the use of such an invisible wrapper? First, it's a perfect subtype, which is the very goal of <code class="sourceCode d"><span class="kw">alias</span> X <span class="kw">this</span></code>. You can add functionalities to your type: new methods, etc. Looks a bit like class inheritance, isn't it? Except that <code class="sourceCode d">Transparent</code> can wrap around (ie: become the subtype of) any type it's aimed at. If you are interested in multiple ways to subtype a type, see section <a href="#library-typedef">Library Typedef</a>, showing Trass3r's library typedef.</p>
<p>Note that this is subtly different from the idea shown in section <a href="#wrapper-templates">Wrapper Templates</a>. In section <a href="#wrapper-templates">Wrapper Templates</a>, use of <code class="sourceCode d">opDispatch</code> lets the wrapper intercept calls <em>before</em> dispatching them. That way, you can add logging to a type, for instance. This is something you cannot do with <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code>. On the other hand, <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code> dispatching is automatically done by the compiler, no need to write intercepting code.</p>
<p>For example, here is another wrapper that gives the description of the held type:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> descriptor;
<span class="kw">import</span> std.stdio;

<span class="kw">struct</span> Descriptor(T)
{
    T value;
    <span class="kw">alias</span> value <span class="kw">this</span>;

    <span class="dt">string</span> description() @property
    {
        <span class="kw">import</span> std.conv;

        <span class="kw">return</span> <span class="st">&quot;Descriptor holding a &quot;</span> ~ T.<span class="dt">stringof</span>
             ~ <span class="st">&quot; of value &quot;</span> ~ to!<span class="dt">string</span>(value) ~ <span class="st">&quot;.\n&quot;</span>
             ~ <span class="st">&quot;(sizeof: &quot;</span> ~ to!<span class="dt">string</span>(T.<span class="dt">sizeof</span>) ~ <span class="st">&quot; bytes)&quot;</span>;
    }
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> d = Descriptor!<span class="dt">double</span>(<span class="fl">1.0</span>);
    writeln(d.description); <span class="co">// &quot;Descriptor holding a double of value 1</span>
                            <span class="co">//  (sizeof: 8 bytes)&quot;</span>
}</code></pre>
<p>One day, D will get multiple <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code>, since it's described in TDPL (<a href="#TDPL">TDPL</a>). This will open the possibility of a type being subtype to many other types at the same time, literally acting as a chameleon depending on circumstances. We will be able to group disparate types and functionalities in one place. I wait for it with increasing interest.<a href="#fn11" class="footnoteRef" id="fnref11"><sup>11</sup></a></p>
<p>However, as far as I'm concerned, the main interest of this subtyping is not so much the possibility to add `parallel' functionality as encoding information in the type itself. See the next section:</p>
<h3 id="library-typedef">Library Typedef</h3>
<p>As we've seen in the previous section, <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code> gives the perfect subtype, able to mimic its parent type in all circumstances. But what if another derived types is needed? D used to have a <code class="sourceCode d"><span class="kw">typedef</span></code> keyword to defines a new type (as opposed to <code class="sourceCode d"><span class="kw">alias</span></code> redefinition which just define a new symbol/name for a type), but it was dropped from the language in 2011. However, the need to define new types in relation with pre-existing types is still there. Templates can help in defining a library-level solution, which is described here.</p>
<p>Mainly, when a new type is defined in relation with another, already existing, target type, there can be four different relationships shown in the following figure:</p>
<div class="figure">
<embed src="typedef.pdf" /><p class="caption">Typedef relationships</p>
</div>
<dl>
<dt>subtype</dt>
<dd><p>That's the standard subclass or <code class="sourceCode d"><span class="kw">alias</span> <span class="kw">this</span></code> relationship: a subtype can act <em>in lieu of</em> its parent type in all circumstances. Whatever its parent can do, the subtype does also. Moreover, the subtype can be forcibly cast as its parent type (think classes).</p>
</dd>
<dt>supertype</dt>
<dd><p>The converse: a supertype can be assigned a value of type 'target', its subtype (since a subtype can act as its supertype), and that's about it. Once the supertype and functions acting on it are created, the original target type can be used there also.</p>
</dd>
<dt>parallel</dt>
<dd><p>A parallel type is neither a subtype not a supertype of the original target (it cannot mimic the target), but it can be created with target values. It's more or less the behaviour of the now-deceased <code class="sourceCode d"><span class="kw">typedef</span></code> keyword.</p>
</dd>
<dt>independent</dt>
<dd><p>An independent type is just there and bears no relationship whatsoever with the original, target type. I cite it there but the interest of defining such a type while still having a 'target' type in mind is limited...</p>
</dd>
</dl>
<p>Here is clean little piece of code from Trass3r that groups all these notions in one template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> librarytypedef;

<span class="kw">enum</span> Relationship
{
    Independent,
    Super,
    Sub,
    Parallel,
}

<span class="kw">struct</span> Typedef( Target,
                Relationship relation = Relationship.Sub,
                Target init = Target.<span class="dt">init</span>,
                <span class="dt">string</span> _f = __FILE__,
                <span class="dt">int</span> _l = __LINE__ )
{
    Target payload = init;

    <span class="kw">static</span> <span class="kw">if</span> ( relation != Relationship.Independent )
        <span class="kw">this</span>( Target value )
        {
            payload = value;
        }

    <span class="kw">static</span> <span class="kw">if</span> ( relation == Relationship.Sub)
        <span class="co">// typedef int foo; foo f;</span>
        <span class="co">// f.opCast!(t)() == cast(t) f</span>
        Target opCast(Target)()
        {
            <span class="kw">return</span> payload;
        }

    <span class="kw">static</span> <span class="kw">if</span> ( relation == Relationship.Sub
             || relation == Relationship.Parallel )
        <span class="kw">alias</span> payload <span class="kw">this</span>;

    <span class="kw">static</span> <span class="kw">if</span> ( relation == Relationship.Super )
        <span class="dt">typeof</span>( <span class="kw">this</span> ) opAssign( Target value )
        {
            payload = value;
            <span class="kw">return</span> <span class="kw">this</span>;
        }
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> ( relation == Relationship.Sub )
        @disable <span class="dt">void</span> opAssign( Target value );
}</code></pre>
<blockquote>
<p><strong>TODO</strong> Give some examples.</p>
</blockquote>
<h2 id="types-as-information">Types as Information</h2>
<h3 id="user-defined-literals">User-Defined Literals</h3>
<p>In <a href="http://drdobbs.com/blogs/tools/229401068">http://drdobbs.com/blogs/tools/229401068</a>, Walter Bright makes a convincing case for using templates as user-defined literals. His example is now the <a href="http://dlang.org/phobos/std_conv.html#octal">std.conv.octal</a> wrapper that allowed D to (see if it's possible to) ditch octal literals as a compiler construct and push them into library-space. That way, you can use:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> o1 = octal!<span class="st">&quot;755&quot;</span>;
<span class="co">// or even:</span>
<span class="kw">auto</span> o2 = octal!<span class="dv">755</span>;</code></pre>
<p>as a stand-in replacement for the <code class="sourceCode d"><span class="bn">0755</span></code> octal literal. It's no more complicated to type (a few chars to add at most), it's clearer for a reader of your code (who may miss the beginning <code class="sourceCode d"><span class="dv">0</span></code>) that he's dealing with an octal there. Best of all, the implementation is there as library code: easy to reach, easy to debug, less intimidating than diving into compiler code, and easy to duplicate for other encodings. That way, this could be done:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> h1 = hexa!<span class="st">&quot;deadbeef&quot;</span>;
<span class="kw">auto</span> b1 = binary!<span class="dv">1011011</span>;
<span class="co">// Or even:</span>
<span class="kw">auto</span> number = base!(<span class="dv">36</span>, <span class="st">&quot;4d6r7th2h7y&quot;</span>);</code></pre>
<p>Behind the scene, <code class="sourceCode d">octal</code> reads its <code class="sourceCode d"><span class="dt">string</span></code> or <code class="sourceCode d"><span class="dt">int</span></code> argument and converts it into an <code class="sourceCode d"><span class="dt">int</span></code> or a <code class="sourceCode d"><span class="dt">long</span></code> depending on the argument size. It's a nice piece of work that could pave the way to similar well-integrated language extensions.</p>
<blockquote>
<p><strong>Unfinished</strong> Also, DSL in strings in D, see <a href="#statically-checked-writeln">Statically-Checked Writeln</a>, <a href="#encoding-information-with-types">Encoding Informations with Types</a> and <a href="#annotating-types">Annotating Types</a>).</p>
</blockquote>
<h3 id="encoding-information-with-types">Encoding Information With Types</h3>
<p>This is an extension of the previous section's idea, that can be found for example in <a href="http://dlang.org/phobos/std_range.html#assumeSorted">std.range.assumeSorted</a> and <a href="http://dlang.org/phobos/std_range.html#SortedRange">std.range.SortedRange</a>. These Phobos constructs encode some information in a type (in this case, the fact than the range is sorted, with an associated predicate). That way, subsequent operations acting on a range can use better algorithm if they know it's sorted.</p>
<p>This kind of encoding can be used for many different schemes:</p>
<ul>
<li>For a matrix library, you could have a, for example, <code class="sourceCode d">assumeHermitian</code> or <code class="sourceCode d">assumeTriangular</code> that just wraps a pre-existing matrix.</li>
<li>For a XML/HTML library, you could imagine a <code class="sourceCode d">Validated</code> struct that's used to indicate, er, validated content. Any external input will have to pass trough a <code class="sourceCode d">validate</code> function that delivers the <code class="sourceCode d">Validated</code> object. Subsequent operations will work only on <code class="sourceCode d">Validated</code> data, not raw data.</li>
<li>A units library (as in, <span class="math"><em>k</em><em>g</em>.<em>m</em>/<em>s</em><sup>2</sup></span>, not unit-testing) is mainly a bunch of <code class="sourceCode d"><span class="dt">double</span></code> (or complex) values wrapped in a multi-checked type that allows only some operations, depending on types. <code class="sourceCode d">meter(<span class="dv">5</span>) + kilo(gram(<span class="dv">10</span>))</code> is a no-no, but <code class="sourceCode d">meter(<span class="dv">5</span>)*kilo(gram(<span class="dv">10</span>))</code> is OK.</li>
</ul>
<p>Moreover, it's easy to provide additional information:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">struct</span> MinMax(T)
{
    T min;
    T max;

    T value;

    <span class="kw">alias</span> value <span class="kw">this</span>;
}</code></pre>
<p>In this case, <code class="sourceCode d">MinMax</code> means the wrapped value is between <code class="sourceCode d">min</code> and <code class="sourceCode d">max</code> (the enforcing code would be in the factory function, for example).</p>
<p>Things get interesting when using multiple wrappers inside one another. Imagine we have three wrappers, for numerical ranges with an ordering operation:</p>
<ul>
<li><code class="sourceCode d">minmaxed</code>, which ascertains (well, at least transmits the message) that the wrapped value is between to extrema.</li>
<li><code class="sourceCode d">periodic</code>, which encodes the idea that a range has a period, accessible through the <code class="sourceCode d">.period</code> member.</li>
<li><code class="sourceCode d">derivative</code>, which says successive elements' difference is no more than a <code class="sourceCode d">.slope</code> number (in absolute).</li>
</ul>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.range: cycle;

<span class="kw">auto</span> range = cycle([<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>,<span class="dv">3</span>,<span class="dv">2</span>,<span class="dv">1</span>]);
<span class="kw">auto</span> withMetadata = minmaxed(
                              periodic(
                                       derivative( range
                                                 , <span class="dv">1</span>)
                                      , <span class="dv">8</span>
                            , <span class="dv">0</span>, <span class="dv">10</span>);

<span class="kw">assert</span>(withMetadata.period == <span class="dv">8</span>); <span class="co">// propagated all the way up.</span></code></pre>
<p>So, in the previous sample, <code class="sourceCode d">withMetadata</code>'s elements are at the same time limited in variation, limited in value and periodic. The trouble is when we want to shift metadata around, comparing types with metadata ordered in a different way: obviously for us humans, a range with suprema and periodic is <em>also</em> periodic and with suprema. But as far as D is concerned a <code class="sourceCode d">minmaxed(periodic())</code> and a <code class="sourceCode d">periodic(minmaxed())</code> do not have the same type. For more on this notion, see section <a href="#annotatingtypes">annotatingtypes</a> on annotating types.</p>
<blockquote>
<p><strong>TODO</strong> A unit example in the Examples part? It may be a bit big...</p>
</blockquote>
<h2 id="templates-in-templates">Templates in Templates</h2>
<p>Sometimes, you know users of your code will send to your template a first list (of indefinite length) of parameters, followed by a second list. Seeing that, you may want to write code like the following:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> MyTemp(A..., B...)
{ ... }</code></pre>
<p>Alas, two template parameters tuples do not make sense (see <a href="#template-declarations">Template Declarations</a>. But it's not a dead-end. First, you could try to write:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span>(AB...)
{ ... }</code></pre>
<p>And filter the <code class="sourceCode d">AB</code>s to find the ones you need. It can be done by <code class="sourceCode d">staticFilter</code>, presented in <a href="#filtering-type-tuples">Static Filter</a> (and its associated function on a function arguments would be <code class="sourceCode d">tupleFilter</code> shown in <a href="#filtering-tuples">Filtering Tuples</a>). In this case, the two series of arguments can be completely mixed (and not separated in two lists), which is strictly more powerful. On the other hand, it means you must be able to separate them by their types alone, which may not be possible.</p>
<h3 id="templates-all-the-way-down">Templates All the Way Down</h3>
<p>Happily, the initial problem can easily be solved this way:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> MyTemp(A...)
{
    <span class="kw">template</span> MyTemp(B...)
    {
    (...)
    }
}</code></pre>
<p>Remember, a template can have template members. So you can nest templates within templates, each with its own constraints and intermediate code. If you use the same name through and through the eponymous trick will be activated, but sometimes using a different name at each stage can make your code more readable.</p>
<p>For example, what if you want to compare two template tuples to see if they contain the same arguments?</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> compare;

<span class="kw">template</span> Compare(First...)
{
    <span class="kw">template</span> With(Second...)
    {
        <span class="kw">static</span> <span class="kw">if</span> (First.<span class="dt">length</span> != Second.<span class="dt">length</span>)
            <span class="kw">enum</span> With = <span class="kw">false</span>;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (First.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// End of comparison</span>
            <span class="kw">enum</span> With = <span class="kw">true</span>;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (!<span class="kw">is</span>(First[<span class="dv">0</span>] == Second[<span class="dv">0</span>]))
            <span class="kw">enum</span> With = <span class="kw">false</span>;
        <span class="kw">else</span>
            <span class="kw">enum</span> With = Compare!(First[<span class="dv">1</span>..$]).With!(Second[<span class="dv">1</span>..$]);
    }
}

<span class="co">//Usage:</span>
<span class="kw">unittest</span>
{
    <span class="kw">alias</span> Compare!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>).With!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">char</span>) C;
    <span class="kw">static</span> <span class="kw">assert</span>(C == <span class="kw">false</span>);
}</code></pre>
<p>In that case, using <code class="sourceCode d">With</code> inside <code class="sourceCode d">Compare</code> let the code be quite easy to use. Notice that the eponymous trick is done only on <code class="sourceCode d">With</code>, because it's this inner template that we want the result of.</p>
<p>Going back to <code class="sourceCode d">MyTemp</code>, using it is slightly more complicated:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="co">// Yes:</span>
<span class="kw">alias</span> MyTemp!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>) MyTemp1;
MyTemp1!(<span class="dt">char</span>, <span class="dt">void</span>);

<span class="co">// No:</span>
MyTemp!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>)!(<span class="dt">char</span>, <span class="dt">void</span>);
<span class="co">// No :</span>
MyTemp!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>).!(<span class="dt">char</span>, <span class="dt">void</span>);</code></pre></td></tr></table>
<p>The D grammar does not authorize multiple template calls like the ones on lines 6 and 8. You must use an alias for the intermediate stage. It's not that drastic a limitation, because if you created the template as a multi-step construction, it's most probably because you wanted to do a multi-step invocation...</p>
<h3 id="double-stage-function-templates">Double-Stage Function Templates</h3>
<p>For function templates, this can give very powerful things. You can have a place in your code where compile-time parameters are given, which delivers another, crafted-just-for-your-needs, template which you can instantiate later on. See for example <a href="#simple-string-interpolation">String Interpolation</a> and the <code class="sourceCode d">interpolate</code> function-in-template.</p>
<p>Policies are particularly good with this idiom. Section <a href="#memoizing-a-function">Memoizing a Function</a> presents a template that transforms a standard D function into a memoized one. Here is what could be done if it was a two-steps template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/*</span>
<span class="co"> * memoizer will store the first million tuple of args</span>
<span class="co"> * and discard half of them when the maximum is reached,</span>
<span class="co"> * to free some memory. At this stage, the function it</span>
<span class="co"> * will memoize is not known. The user decided this</span>
<span class="co"> * particular instantiation was the best memoizing</span>
<span class="co"> * strategy in her code. memoizer could (and will!) be</span>
<span class="co"> * applied on many different functions.</span>
<span class="co"> */</span>
<span class="kw">alias</span> memoize!( Storing.maximum
              , <span class="dv">1_000_000</span>
              , Discarding.fraction
              , <span class="fl">0.5f</span>
              ) memoizer;

<span class="kw">auto</span> longCalculation1(<span class="dt">int</span> i, <span class="dt">double</span> d) { ... }
<span class="kw">auto</span> longCalculation2(<span class="dt">double</span> d, <span class="dt">string</span> s) { ... }

<span class="co">/*</span>
<span class="co"> * longCalculation1 and longCalculation2 will both profit</span>
<span class="co"> * from the memoization even though they have different</span>
<span class="co"> * signatures, different arguments and return a different type.</span>
<span class="co"> */</span>
<span class="kw">alias</span> memoizer!longCalculation1 mlc1;
<span class="kw">alias</span> memoizer!longCalculation2 mlc2;</code></pre>
<blockquote>
<p><strong>TODO</strong> OK, now maybe I should provide an updated version of <code class="sourceCode d">memoize</code> in <a href="#memoizing-a-function">Memoizing a Function</a>.</p>
</blockquote>
<h3 id="named-fields-tuples">Named-Fields Tuples</h3>
<p>Let's have another example, to use <a href="#ifti">IFTI</a>. In Phobos, the function <a href="http://dlang.org/phobos/std_typecons.html#tuple">std.typecons.tuple</a> lets you create a tuple on the fly. It's a very nice example of IFTI in action:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingtuple;
<span class="kw">import</span> std.typecons;

<span class="dt">void</span> main()
{
    <span class="co">// tuple1 is a Tuple!(int,double,string)</span>
    <span class="kw">auto</span> tuple1 = tuple(<span class="dv">1</span>, <span class="fl">3.14159</span>, <span class="st">&quot;abc&quot;</span>);
    <span class="co">// tuple2 is a Tuple!(char,char,char)</span>
    <span class="kw">auto</span> tuple2 = tuple(<span class="ch">&#39;a&#39;</span>,<span class="ch">&#39;b&#39;</span>,<span class="ch">&#39;c&#39;</span>);
}</code></pre>
<p>But Phobos' <code class="sourceCode d">Tuple</code> is more powerful than that. It can have named parameters:</p>
<pre class="sourceCode d"><code class="sourceCode d">Tuple!(<span class="dt">int</span>, <span class="st">&quot;counter&quot;</span>, <span class="dt">string</span>, <span class="st">&quot;name&quot;</span>) myCounter;
myCounter.counter = -<span class="dv">1</span>;
myCounter.name = <span class="st">&quot;The One and Only Counter Around There&quot;</span>;</code></pre>
<p>As of this writing, Phobos doesn't provide a <code class="sourceCode d">tuple</code> factory function allowing named arguments in an nice, automated manner. Here is what I'd like to have:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingnamedtuple;
<span class="kw">import</span> namedtuple;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> myCounter = tuple!(<span class="st">&quot;counter&quot;</span>, <span class="st">&quot;name&quot;</span>)
                           (-<span class="dv">1</span>, <span class="st">&quot;Who&#39;s his Daddy&#39;s counter?&quot;</span>);

    myCounter.counter = <span class="dv">1</span>;

    <span class="co">// Or even:</span>
    <span class="kw">alias</span> tuple!(<span class="st">&quot;counter&quot;</span>, <span class="st">&quot;name&quot;</span>) makeCounter;

    <span class="kw">auto</span> c1 = makeCounter(<span class="dv">0</span>, <span class="st">&quot;I count ints!&quot;</span>);
    <span class="kw">auto</span> c2 = makeCounter(<span class="st">&quot;Hello&quot;</span>, <span class="st">&quot;I&#39;m a strange one, using strings&quot;</span>);

    c2.counter ~= <span class="st">&quot; World!&quot;</span>;
}</code></pre>
<p>In the previous example, <code class="sourceCode d">c1</code> is a <code class="sourceCode d">Tuple!(<span class="dt">int</span>, <span class="dt">string</span>)</code>, whereas <code class="sourceCode d">c2</code> is a <code class="sourceCode d">Tuple!(<span class="dt">string</span>, <span class="dt">string</span>)</code>. That means <code class="sourceCode d">makeCounter</code> is a factory function for tuples with two fields, named <code class="sourceCode d">counter</code> and <code class="sourceCode d">name</code>, which see their types determined later on. I want this, so let's code it.</p>
<p>First, it's obvious we need a two-stage template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.typetuple: allSatisfy;

<span class="kw">template</span> tuple(names...)
<span class="kw">if</span> (names.<span class="dt">length</span> &amp;&amp; allSatisfy!(isAStringLiteral, names))
{
    <span class="kw">auto</span> tuple(T...)(T args)
    {
    (...)
    }
}</code></pre>
<p>The constraint is here to check that the user gives at least one name and also that all passed <code class="sourceCode d">names</code> are indeed string literals template parameters. I use <a href="http://dlang.org/phobos/std_typetuple.html#allSatisfy">std.typetuple.allSatisfy</a> to verify the condition on all of them. I cannot use directly <a href="http://dlang.org/phobos/std_traits.html#isSomeString">std.traits.isSomeString</a> because this template acts on types, whereas I need something checking a string literal.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> isastringliteral;
<span class="kw">import</span> std.traits: isSomeString;

<span class="kw">template</span> isAStringLiteral(<span class="kw">alias</span> name)
{
    <span class="kw">enum</span> isAStringLiteral = isSomeString!(<span class="dt">typeof</span>(name));
}</code></pre>
<p>That being in place, we need to create the correct <code class="sourceCode d">Tuple</code>. Arguments names are provided right after each type (so as to allow for a mix between named and anonymous fields:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/*</span>
<span class="co"> * The first two fields are named, and the fourth.</span>
<span class="co"> * The third is anonymous.</span>
<span class="co"> */</span>
<span class="kw">alias</span> Tuple!( <span class="dt">int</span>,    <span class="st">&quot;counter&quot;</span>
            , <span class="dt">string</span>, <span class="st">&quot;name&quot;</span>
            , <span class="dt">double</span>  <span class="co">/* Anonymous */</span>
            , <span class="dt">double</span>, <span class="st">&quot;total&quot;</span>
            ) MyTuple;</code></pre>
<p>For our function, we consider that, given <span class="math"><em>n</em></span> names, the first <span class="math"><em>n</em></span> arguments will be named and the remaining (if any) will be anonymous. That give us another constraint: if the user provide less than <span class="math"><em>n</em></span> arguments, we refuse the input and stop the compilation right there.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.typetuple: allSatisfy;

<span class="kw">template</span> tuple(names...)
<span class="kw">if</span> (names.<span class="dt">length</span> &amp;&amp; allSatisfy!(isAStringLiteral, names))
{
    <span class="kw">auto</span> tuple(T...)(T args) <span class="kw">if</span> (T.<span class="dt">length</span> &gt;= names.<span class="dt">length</span>)
    {
    (...)
    }
}</code></pre>
<p>Now, we just need the alternate the names and the argument types. Happily, this document describes a <code class="sourceCode d">Interleave</code> template in <a href="#interleaving-types">Interleaving Types</a>, that does just that:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> namedtuple;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> interleave;
<span class="kw">import</span> isastringliteral;

<span class="kw">template</span> tuple(names...)
<span class="kw">if</span> (names.<span class="dt">length</span> &amp;&amp; allSatisfy!(isAStringLiteral, names))
{
    <span class="kw">auto</span> tuple(T...)(T args) <span class="kw">if</span> (T.<span class="dt">length</span> &gt;= names.<span class="dt">length</span>)
    {
        <span class="kw">return</span> Tuple!(Interleave!(T).With!(names))(args);
    }
}</code></pre>
<p>And, presto, here we have our named-tuple factory function. Isn't that nice? The closure example in <a href="#closures-are-a-poor-mans-objects">Closures Are A Poor Man's Objects</a> could use it to simplify its returned value.</p>
<blockquote>
<p><strong>TODO</strong> And a curried template.</p>
</blockquote>
<h2 id="file__-and-__line__"><code>__FILE__</code> and <code>__LINE__</code></h2>
<blockquote>
<p><strong>Unfinished</strong> This section needs some heavy testing. My D config was broken when I wrote this part. Take everything in there with a <em>big</em> grain of salt. It's on my todo list to test and rewrite everything.</p>
</blockquote>
<p>In section <a href="#default-values">Default Values</a>, we've seen that template parameters can have default values. There are also two special, reserved, symbols that are defined in D: <code class="sourceCode d">__FILE__</code> and <code class="sourceCode d">__LINE__</code>. They are used in standard (non-<code class="sourceCode d"><span class="kw">mixin</span></code>) templates, but their behaviour will remind you of mixins: when instantiated, they get replaced by strings containing the file name and the line in the file of the <em>instantiation call site</em>. Yes, it's a sort of two-way dialogue: module <code class="sourceCode d">a.d</code> defines template <code class="sourceCode d">T</code>. Module <code class="sourceCode d">b.d</code> asks for a <code class="sourceCode d">T</code> instantiation. This instantiation is done in module <code class="sourceCode d">a.d</code>, but will line and filename taken from <code class="sourceCode d">b.d</code>!</p>
<p>They are mostly declared like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> filelinetagging;

<span class="kw">struct</span> Unique(T, <span class="dt">string</span> file, <span class="dt">size_t</span> line)
{
    <span class="kw">enum</span> <span class="dt">size_t</span> l = line;
    <span class="kw">enum</span> <span class="dt">string</span> f = file;
    T t;
}

<span class="kw">auto</span> unique(T, <span class="dt">string</span> file = __FILE__, <span class="dt">size_t</span> line = __LINE__)(T t)
{
    <span class="kw">return</span> Unique!(T, file, line)(t);
}</code></pre>
<p>As <code class="sourceCode d">Unique</code>'s name suggests, this is a way to obtain unique instantiations. Except if you call the very same template twice in the same line of your file, this pretty much guarantee your instantiation will be the only one. Remember that template arguments become part of the template scope name when instantiation is done (<a href="#instantiating-a-template">Instantiating a Template</a>).</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingunique;
<span class="kw">import</span> filelinetagging;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> u = unique(<span class="dv">1</span>); <span class="co">// Unique!(int, &quot;thefile.d&quot;, 4)</span>

    <span class="kw">auto</span> v = unique(<span class="dv">1</span>); <span class="co">// Unique!(int, &quot;thefile.d&quot;, 6)</span>

    <span class="kw">static</span> <span class="kw">assert</span>(!<span class="kw">is</span>( <span class="dt">typeof</span>(v) == <span class="dt">typeof</span>(u) ));
}</code></pre>
<p>Even though <code class="sourceCode d">u</code> and <code class="sourceCode d">v</code> are declared the same way, they have different types.</p>
<p>Apart from <em>one-of-a-kind</em> types, this is also useful for debugging: you can use the strings in error messages:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> flatten(Range, file == __FILE__, line == __LINE__)(Range range)
{
    <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">0</span>)
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;File: &quot;</span> ~ file ~ <span class="st">&quot; at line: &quot;</span> ~ line
                       ~ <span class="st">&quot;, flatten called with a rank-0 type: &quot;</span>
                       ~ Range.<span class="dt">stringof</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (rank!Range == <span class="dv">1</span>)
        <span class="kw">return</span> range;
    <span class="kw">else</span>
        <span class="kw">return</span> Flatten!(Range)(range);
}</code></pre>
<p>And here is a little gift:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> debugger;

<span class="co">/** Usage:</span>
<span class="co"> * Debug!(templateToBeTested).With!(Argument0, Argument1, Argument2);</span>
<span class="co"> */</span>
<span class="kw">template</span> Debug(<span class="kw">alias</span> toTest, <span class="dt">string</span> file = __FILE__, <span class="dt">size_t</span> line = __LINE__)
{
    <span class="kw">template</span> With(Args...)
    {
        <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>( toTest!Args ))
            <span class="kw">alias</span> toTest!Args With;
        <span class="kw">else</span>
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;Error: &quot;</span> ~ to!<span class="dt">string</span>(toTest)
                           ~ <span class="st">&quot; called withs arguments: &quot;</span>
                           ~ Args.<span class="dt">stringof</span>);
    }
}</code></pre>
<p>That way, no need to modify your beautiful templates.</p>
<blockquote>
<p><strong>TODO</strong> Test that.</p>
</blockquote>
<h1 id="around-templates-other-compile-time-tools">Around Templates: Other Compile-Time Tools</h1>
<p>There is more to compile-time metaprogramming in D than <em>just</em> templates. This part will describe the most common tools: <a href="#string-mixins">string mixins</a>, <a href="#compile-time-function-evaluation">compile-time function evaluation (CTFE)</a> and <a href="#traits"><code>__traits</code></a>, as seen in relation with templates. For the good news is: they are all interoperable. String mixins are wonderful to inject code in your templates, compile-time-evaluable functions can act as template parameters and can be templated. And, best of best, templated compile-time functions can return strings which can in turn be mixed-in in your templates. Come and see, it's fun!</p>
<h2 id="string-mixins">String Mixins</h2>
<p>String mixins put D code were they are called, just before compilation. Once injected, the code is <em>bona fide</em> D code, like any other. Code is manipulated as strings, hence the name.</p>
<h3 id="syntax-9">Syntax</h3>
<p>The syntax is slightly different from <a href="#mixin-templates">mixin templates</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">mixin</span>(<span class="st">&quot;some code as a string&quot;</span>);</code></pre>
<p>You must take care not to forget the parenthesis. String mixins are a purely compile-time tool, so the string must also be determined at compile-time.</p>
<h3 id="mixing-code-in-with-templates">Mixing Code In, With Templates</h3>
<p>Of course, just injecting predefined code is a bit boring:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">mixin</span>(<span class="st">&quot;int i = 3;&quot;</span>); <span class="co">// Do not forget the two semicolons</span>
                     <span class="co">// one for the mixed-in code,</span>
                     <span class="co">// one for the mixin() call.</span>
i++;
<span class="kw">assert</span>(i == <span class="dv">4</span>);</code></pre>
<p>There is no interest in that compared to directly writing standard D code. The fun begins with D powerful constant folding ability: in D, strings can be concatenated at compile-time. That's where string mixins meet templates: templates can produce strings at compile-time and can get strings as parameters. You already saw that in section <a href="#operator-overloading">Operator Overloading</a> and section <a href="#opdispatch"><code>opDispatch</code></a>, since I couldn't help doing a bit of foreshadowing.</p>
<p>Now, imagine for example wanting a template that generates structs for you. You want to be able to name the structs as you wish. Say we would like the usage to look like that:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingmystruct1;
<span class="kw">import</span> mystruct1;

<span class="kw">mixin</span>(MyStruct!<span class="st">&quot;First&quot;</span>);  <span class="co">// creates a new type called First (a struct)</span>
<span class="kw">mixin</span>(MyStruct!<span class="st">&quot;Second&quot;</span>); <span class="co">// and another one called Second</span>

<span class="dt">void</span> main()
{
    <span class="co">// &quot;First&quot; code was injected right there, in module &#39;mine&#39;.</span>
    First f1, f2;
    Second s1;

    <span class="kw">assert</span>(<span class="kw">is</span>( <span class="dt">typeof</span>(f1) == First));
}</code></pre>
<p>Here comes the generating code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> mystruct1;

<span class="kw">template</span> MyStruct(<span class="dt">string</span> name)
{
    <span class="kw">enum</span> <span class="dt">string</span> MyStruct = <span class="st">&quot;struct &quot;</span> ~ name
                         ~ <span class="st">&quot; { &quot;</span>
                         ~ <span class="st">&quot;/+ some code +/&quot;</span>
                         ~ <span class="st">&quot; }&quot;</span>;
}

<span class="co">// For example, with name == &quot;First&quot;, it will return</span>
<span class="co">//   &quot;struct First { /+ some code +/ }&quot;</span>
<span class="co">//</span></code></pre>
<p>In this case, the string is assembled inside the template during instantiation, exposed through the eponymous trick and then mixed in where you want it. Note that the string is generated in the <code class="sourceCode d">utils</code> module containing <code class="sourceCode d">MyStruct</code>, but that <code class="sourceCode d">First</code> and <code class="sourceCode d">Second</code> are defined exactly where the <code class="sourceCode d"><span class="kw">mixin</span>()</code> call is. If you use the mixin in different modules, this will define as many different structs, all named the same way. This might be exactly what you want, or not.</p>
<p>To get the same struct type in different modules, the code must be organized a bit differently: the structs must be generated in the template module.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> mystruct2;

<span class="kw">template</span> MyStruct(<span class="dt">string</span> name)
{
    <span class="kw">alias</span> MyStructImpl!(name).result MyStruct;
}

<span class="kw">template</span> MyStructImpl(<span class="dt">string</span> name)
{
    <span class="kw">enum</span> <span class="dt">string</span> code = <span class="st">&quot;struct &quot;</span> ~ name
                     ~ <span class="st">&quot; { &quot;</span>
                     ~ <span class="st">&quot;/+ some code +/&quot;</span>
                     ~ <span class="st">&quot; }&quot;</span>;
    <span class="kw">mixin</span>(code);
    <span class="kw">mixin</span>(<span class="st">&quot;alias &quot;</span> ~ name ~ <span class="st">&quot; result;&quot;</span>);
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingmystruct2;
<span class="kw">import</span> mystruct2;

MyStruct!<span class="st">&quot;First&quot;</span> f1, f2;
MyStruct!<span class="st">&quot;Second&quot;</span> s1;</code></pre>
<p>Usage is a different, as you can see. In this case, <code class="sourceCode d">First</code> is generated inside <code class="sourceCode d">MyStructImpl</code> and exposed through an alias (this particular alias statement is itself generated by a string mixin). In fact, the entire code could be put in the mixin:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> mystruct3;

<span class="kw">template</span> MyStruct(<span class="dt">string</span> name)
{
    <span class="kw">alias</span> MyStructImpl!(name).result MyStruct;
}

<span class="kw">template</span> MyStructImpl(<span class="dt">string</span> name)
{
<span class="kw">mixin</span>(<span class="st">&quot;struct &quot;</span> ~ name
    ~ <span class="st">&quot; {&quot;</span>
    ~ <span class="st">&quot;/* some code */&quot;</span>
    ~ <span class="st">&quot; }\n&quot;</span>
    ~ <span class="st">&quot;alias &quot;</span> ~ name ~ <span class="st">&quot; result;&quot;</span>);
}</code></pre>
<p>Here is an example using the ternary <code class="sourceCode d">?:</code> operator to do some compile-time selection of code, similar to what can be done with <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> (<a href="#static-if">Static If</a>):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> getset2;

<span class="kw">enum</span> GetSet { no, yes}

<span class="kw">struct</span> S(GetSet getset = GetSet.no, T)
{
    <span class="kw">enum</span> priv = <span class="st">&quot;private T value;\n&quot;</span>
              ~ <span class="st">&quot;T get() @property { return value;}\n&quot;</span>
              ~ <span class="st">&quot;void set(T _value) { value = _value;}&quot;</span>;

    <span class="kw">enum</span> pub = <span class="st">&quot;T value;&quot;</span>;

    <span class="kw">mixin</span>( (getset == GetSet.yes) ? priv : pub);
}</code></pre>
<p>The code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> getset2;

<span class="dt">void</span> main()
{
    S!(GetSet.yes, <span class="dt">int</span>) gs;
    gs.set(<span class="dv">1</span>);
    <span class="kw">assert</span>( gs.get == <span class="dv">1</span>);
}</code></pre>
<p>generates:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">struct</span> S!(GetSet.yes, <span class="dt">int</span>)
{
    <span class="kw">private</span> <span class="dt">int</span> value;
    <span class="dt">int</span> get() @property { <span class="kw">return</span> value;}
    <span class="dt">void</span> set(<span class="dt">int</span> _value) { value = _value;}
}</code></pre>
<h3 id="limitations">Limitations</h3>
<p>Code crafting is still a bit awkward, because I haven't introduced CTFE yet (see <a href="#compile-time-function-evaluation">CTFE</a>). So we are limited to simple concatenation for now: looping for example is possible with templates, but far easier with CTFE. Even then, it's already wonderfully powerful: you can craft D code with some `holes' (types, names, whatever) that will be completed by a template instantiation and then mixed in elsewhere. You can create other any kind of D code with that.</p>
<p>You can put <code class="sourceCode d"><span class="kw">mixin</span>()</code> expressions almost were you want to, but...</p>
<blockquote>
<p><strong>TODO</strong> Test the limits:inside static if expressions, for example</p>
</blockquote>
<blockquote>
<p><strong>Escaping strings.</strong> One usual problem with manipulating D code as string is how to deal with strings in code? You must escape them. Either use <code>\&quot;</code> to create string quotes, a bit like was done in section <a href="#function-templates">Function Template Syntax</a> to generate the error message for <code class="sourceCode d">select</code>. Or you can put strings between <code class="sourceCode d">q{</code> and <code>}</code> or between backquotes.</p>
</blockquote>
<h2 id="compile-time-function-evaluation">Compile-Time Function Evaluation</h2>
<h3 id="evaluation-at-compile-time">Evaluation at Compile-Time</h3>
<p>Compile-Time Function Evaluation (from now on, CTFE) is an extension of the constant-folding that's done during compilation in D code: if you can calculate <code class="sourceCode d"><span class="dv">1</span> + <span class="dv">2</span> + <span class="dv">3</span>*<span class="dv">4</span></code> at compile-time, why not extend it to whole functions evaluation? I'll call evaluable at compile-time functions CTE functions from now on.</p>
<p>It's a very hot topic in D right now and the reference compiler has advanced by leaps and bounds in 2011 and 2012. The limits to what can be done with CTE functions are pushed farther away at each new release. All the <code class="sourceCode d"><span class="kw">foreach</span></code>, <code class="sourceCode d"><span class="kw">while</span></code>, <code class="sourceCode d"><span class="kw">if</span></code>/<code class="sourceCode d"><span class="kw">else</span></code> statements, arrays manipulation, struct manipulation, function manipulation are there. You can even do pointer arithmetics! When I began this document (DMD 2.055), the limitations were mostly: no classes and no exceptions (and so, no <code class="sourceCode d">enforce</code>). This was changed with DMD 2.057, allowing the manipulation of classes at compile-time. DMD 2.058-2.061 then killed a huge amount of CTFE-related bugs.</p>
<p>In fact danger lies the other way round: it's easy to forget that CTE functions must also be standard, runtime, functions. Remember that some actions only make sense at compile-time or with compile-time initialized constants: indexing on tuples for example:</p>
<h3 id="ctfe"><code>__ctfe</code></h3>
<blockquote>
<p><strong>Unfinished</strong> Write something on this new functionality, which enables testing inside a function whether we are at compile-time or runtime.</p>
</blockquote>
<h3 id="templates-and-ctfe">Templates and CTFE</h3>
<blockquote>
<p><strong>Unfinished</strong> Some juicy examples should be added.</p>
</blockquote>
<p>That means: you can feed compile-time constants to your classical D function and its code will be evaluated at compile-time. As far as templates are concerned, this means that function return values can be used as template parameters and as <code class="sourceCode d"><span class="kw">enum</span></code> initializers:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/* */</span></code></pre>
<p>Template functions can very well give rise to functions evaluated at compile-time:</p>
<pre class="sourceCode d"><code class="sourceCode d"></code></pre>
<h3 id="templates-and-ctfe-and-string-mixins-oh-my">Templates and CTFE and String Mixins, oh my!</h3>
<p>And the fireworks is when you mix(!) that with string mixins: code can be generated by functions, giving access to almost the entire D language to craft it. This code can be mixed in templates to produce what you want. And, to close the loop: the function returning the code-as-string can itself be a template, using another template parameters as its own parameters.</p>
<p>Concretly, here is the getting-setting code from section <a href="#getters-and-setters">Getters and Setters</a>, reloaded:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> getset3;
<span class="kw">import</span> std.conv;

<span class="kw">enum</span> GetSet { no, yes}

<span class="dt">string</span> priv(<span class="dt">string</span> type, <span class="dt">string</span> index)
{
    <span class="kw">return</span>
    <span class="st">&quot;private &quot;</span>~type~<span class="st">&quot; value&quot;</span>~index~<span class="st">&quot;;\n&quot;</span>
  ~ type~<span class="st">&quot; get&quot;</span>~index~<span class="st">&quot;() @property { return value&quot;</span>~index~<span class="st">&quot;;}\n&quot;</span>
  ~ <span class="st">&quot;void set&quot;</span>~index~<span class="st">&quot;(&quot;</span>~type~<span class="st">&quot; _value) { value&quot;</span>~index~<span class="st">&quot; = _value;}&quot;</span>;
}

<span class="dt">string</span> pub(<span class="dt">string</span> type, <span class="dt">string</span> index)
{
    <span class="kw">return</span> type ~ <span class="st">&quot;value&quot;</span> ~ index ~ <span class="st">&quot;;&quot;</span>;
}

<span class="dt">string</span> GenerateS(GetSet getset = GetSet.no, T...)()
{
    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(index, Type; T)
        <span class="kw">static</span> <span class="kw">if</span> (getset == GetSet.yes)
             result ~= priv(Type.<span class="dt">stringof</span>, to!<span class="dt">string</span>(index));
        <span class="kw">else</span>
            result ~= pub(Type.<span class="dt">stringof</span>, to!<span class="dt">string</span>(index));
    <span class="kw">return</span> result;
}

<span class="kw">struct</span> S(GetSet getset = GetSet.no, T...)
{
    <span class="kw">mixin</span>(GenerateS!(getset,T));
}

<span class="dt">void</span> main()
{
    S!(GetSet.yes, <span class="dt">int</span>, <span class="dt">string</span>, <span class="dt">int</span>) gs;

<span class="co">/* Generates:</span>
<span class="co">struct S!(GetSet.yes, int, string, int)</span>
<span class="co">{</span>
<span class="co">    private int value0;</span>
<span class="co">    int get0() @property { return value0;}</span>
<span class="co">    void set0(int _value) { value0 = _value;}</span>

<span class="co">    private string value1;</span>
<span class="co">    string get1() @property { return value1;}</span>
<span class="co">    void set1(string _value) { value1 = _value;}</span>

<span class="co">    private int value2;</span>
<span class="co">    int get2() @property { return value2;}</span>
<span class="co">    void set2(int _value) { value2 = _value;}</span>
<span class="co">}</span>
<span class="co">*/</span>

    gs.set1(<span class="st">&quot;abc&quot;</span>);
    <span class="kw">assert</span>(gs.get1 == <span class="st">&quot;abc&quot;</span>);
}</code></pre>
<p>This code is much more powerful than the one we saw previously: the number of types is flexible, and an entire set of getters/setters is generated when asked to. All this is done by simply plugging <code class="sourceCode d"><span class="dt">string</span></code>-returning functions together, and a bit of looping by way of a compile-time <code class="sourceCode d"><span class="kw">foreach</span></code>.</p>
<h3 id="simple-string-interpolation">Simple String Interpolation</h3>
<p>All this play with the concatenating operator (<code class="sourceCode d">~</code>) is becoming a drag. We should write a string interpolation function, evaluable at compile-time of course, to help us in our task. Here is how I want to use it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> stringinterpolation;

<span class="kw">alias</span> interpolate!<span class="st">&quot;struct #0 { #1 value; #0[#2] children;}&quot;</span> makeTree;

<span class="kw">enum</span> <span class="dt">string</span> intTree = makeTree(<span class="st">&quot;IntTree&quot;</span>, <span class="st">&quot;int&quot;</span>, <span class="dv">2</span>);
<span class="kw">enum</span> <span class="dt">string</span> doubleTree = makeTree(<span class="st">&quot;DoubleTree&quot;</span>, <span class="st">&quot;double&quot;</span>, <span class="st">&quot;&quot;</span>);

<span class="kw">static</span> <span class="kw">assert</span>(intTree
          == <span class="st">&quot;struct IntTree { int value; IntTree[2] children;}&quot;</span>);
<span class="kw">static</span> <span class="kw">assert</span>(doubleTree
          == <span class="st">&quot;struct DoubleTree { double value; DoubleTree[] children;}&quot;</span>);</code></pre>
<p>As you can see, the string to be interpolated is passed as a template parameter. Placeholders use a character normally not found in D code: <code class="sourceCode d">#</code>. The <span class="math"><em>n</em><sup><em>t</em><em>h</em></sup></span> parameter is <code class="sourceCode d">#n</code>, starting from 0. As a concession to practicality, a lone <code class="sourceCode d">#</code> is considered equivalent to <code class="sourceCode d">#<span class="dv">0</span></code>. Args to be put into the string are passed as standard (non-template) parameters and can be of any type.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> stringinterpolation;
<span class="kw">import</span> std.conv;

<span class="kw">template</span> interpolate(<span class="dt">string</span> code)
{
    <span class="dt">string</span> interpolate(Args...)(Args args) {
        <span class="dt">string</span>[] stringified;
        <span class="kw">foreach</span>(index, arg; args) stringified ~= to!<span class="dt">string</span>(arg);

        <span class="dt">string</span> result;
        <span class="dt">int</span> i;
        <span class="dt">int</span> zero = to!<span class="dt">int</span>(<span class="ch">&#39;0&#39;</span>);

        <span class="kw">while</span> (i &lt; code.<span class="dt">length</span>) {
            <span class="kw">if</span> (code[i] == <span class="ch">&#39;#&#39;</span>) {
                <span class="dt">int</span> j = <span class="dv">1</span>;
                <span class="dt">int</span> index;
                <span class="kw">while</span> (i+j &lt; code.<span class="dt">length</span>
                    &amp;&amp; to!<span class="dt">int</span>(code[i+j])-zero &gt;= <span class="dv">0</span>
                    &amp;&amp; to!<span class="dt">int</span>(code[i+j])-zero &lt;= <span class="dv">9</span>)
                {
                    index = index*<span class="dv">10</span> + to!<span class="dt">int</span>(code[i+j])-zero;
                    ++j;
                }

                result ~= stringified[index];
                i += j;
            }
            <span class="kw">else</span> {
                result ~= code[i];
                ++i;
            }
        }

        <span class="kw">return</span> result;
    }
}</code></pre>
<blockquote>
<p><strong>TODO</strong> The syntax could be extended somewhat: inserting multiple strings, inserting a range of strings, all arguments to the end.</p>
</blockquote>
<h3 id="example-extending-std.functional.binaryfun">Example: extending std.functional.binaryFun</h3>
<blockquote>
<p><strong>Unfinished</strong> This one is dear to my heart. Mapping <span class="math"><em>n</em></span> ranges in parallel is one of the first things that I wanted to do with ranges, for examples to create ranges of structs with constructor taking more than one parameter.</p>
</blockquote>
<p>Phobos has two really interesting templates: <a href="http://dlang.org/phobos/std_functional.html#unaryFun">std.functional.unaryFun</a> and <a href="http://dlang.org/phobos/std_functional.html#binaryFun">std.functional.binaryFun</a>.</p>
<blockquote>
<p><strong>TODO</strong> Explain that this aims to extend that to n-args functions.</p>
</blockquote>
<blockquote>
<p><strong>TODO</strong> Augh, the introduction, as of DMD 2.058 of a nice closure syntax more or less alleviate the need for such a construction.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="dt">bool</span> isaz(<span class="dt">char</span> c) {
    <span class="kw">return</span> c &gt;= <span class="ch">&#39;a&#39;</span> &amp;&amp; c &lt;= <span class="ch">&#39;z&#39;</span>;
}

<span class="dt">bool</span> isAZ(<span class="dt">char</span> c) {
    <span class="kw">return</span> c &gt;= <span class="ch">&#39;A&#39;</span> &amp;&amp; c &lt;= <span class="ch">&#39;Z&#39;</span>;
}

<span class="dt">bool</span> isNotLetter(<span class="dt">char</span> c) {
    <span class="kw">return</span> !isaz(c) &amp;&amp; !isAZ(c);
}

<span class="dt">int</span> letternum(<span class="dt">char</span> c) {
    <span class="kw">return</span> to!<span class="dt">int</span>(c) - to!<span class="dt">int</span>(<span class="ch">&#39;a&#39;</span>) + <span class="dv">1</span>;
}

<span class="dt">int</span> arity(<span class="dt">string</span> s) {
    <span class="kw">if</span> (s.<span class="dt">length</span> == <span class="dv">0</span>) <span class="kw">return</span> <span class="dv">0</span>;

    <span class="dt">int</span> arity;
    <span class="dt">string</span> padded = <span class="st">&quot; &quot;</span> ~ s ~ <span class="st">&quot; &quot;</span>;
    <span class="kw">foreach</span>(i, c; padded[<span class="dv">0</span>..$-<span class="dv">2</span>])
        <span class="kw">if</span> (isaz(padded[i+<span class="dv">1</span>])
         &amp;&amp; isNotLetter(padded[i])
         &amp;&amp; isNotLetter(padded[i+<span class="dv">2</span>]))
            arity = letternum(padded[i+<span class="dv">1</span>]) &gt; arity ?
                    letternum(padded[i+<span class="dv">1</span>])
                  : arity;
    <span class="kw">return</span> arity;
}

<span class="dt">string</span> templateTypes(<span class="dt">int</span> arit) {
    <span class="kw">if</span> (arit == <span class="dv">0</span>) <span class="kw">return</span> <span class="st">&quot;&quot;</span>;
    <span class="kw">if</span> (arit == <span class="dv">1</span>) <span class="kw">return</span> <span class="st">&quot;A&quot;</span>;

    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(i; <span class="dv">0</span>..arit)
        result ~= <span class="st">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;</span>[i] ~ <span class="st">&quot;, &quot;</span>;

    <span class="kw">return</span> result[<span class="dv">0</span>..$-<span class="dv">2</span>];
}

<span class="dt">string</span> params(<span class="dt">int</span> arit) {
    <span class="kw">if</span> (arit == <span class="dv">0</span>) <span class="kw">return</span> <span class="st">&quot;&quot;</span>;
    <span class="kw">if</span> (arit == <span class="dv">1</span>) <span class="kw">return</span> <span class="st">&quot;A a&quot;</span>;

    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(i; <span class="dv">0</span>..arit)
        result ~= <span class="st">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;</span>[i]
               ~ <span class="st">&quot; &quot;</span> ~ <span class="st">&quot;abcdefghijklmnopqrstuvwxyz&quot;</span>[i]
               ~ <span class="st">&quot;, &quot;</span>;

    <span class="kw">return</span> result[<span class="dv">0</span>..$-<span class="dv">2</span>];
}

<span class="dt">string</span> naryFunBody(<span class="dt">string</span> code, <span class="dt">int</span> arit) {
    <span class="kw">return</span> interpolate!<span class="st">&quot;auto ref naryFun(#0)(#1) { return #2;}&quot;</span>
                      (templateTypes(arit), params(arit), code);
}

<span class="kw">template</span> naryFun(<span class="dt">string</span> code, <span class="dt">int</span> arit = arity(code))
{
    <span class="kw">mixin</span>(naryFunBody(code, arit));
}</code></pre>
<h3 id="sorting-networks">Sorting Networks</h3>
<p>Sorting networks are a nice example of what compile-time code generation can buy you. Sorting is a very vast subject and obtaining near-optimal sort in many circumstances is quite difficult. But in some cases, if you know your input length, you can build a pre-defined list of comparisons between elements and swap them if they are not in the correct order. Here, I will represent sorting networks as pairs of indices in the input range: given indices <span class="math"><em>i</em></span> and <span class="math"><em>j</em></span>, compare <code class="sourceCode d">input[i]</code> and <code class="sourceCode d">input[j]</code>, and so on.</p>
<p>For example, given an array or a random-access range of length <span class="math"><em>n</em></span>, the following table presents possible (optimal, in this case) sorting networks.</p>
<table>
<caption>the first sorting networks</caption>
<thead>
<tr class="header">
<th align="left">n</th>
<th align="left">Sorting network</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">2</td>
<td align="left">[[0, 1]]</td>
</tr>
<tr class="even">
<td align="left">3</td>
<td align="left">[[0, 2], [0, 1], [1, 2]]</td>
</tr>
<tr class="odd">
<td align="left">4</td>
<td align="left">[[0, 2], [1, 3], [0, 1], [2, 3], [1, 2]]</td>
</tr>
<tr class="even">
<td align="left">5</td>
<td align="left">[[0, 4], [0, 2], [1, 3], [2, 4], [0, 1], [2, 3], [1, 4], [1, 2], [3, 4]]</td>
</tr>
</tbody>
</table>
<p>The code to generate the list of indices can be found in Knuth's <em>The Art of Computer Programming</em> or on the net. The code given below I translated from Common Lisp (!) to D, and is taken from Doug Hoyte's <a href="http://letoverlambda.com">Let Over Lambda</a>, a very opinionated book about Common Lisp's macros.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> sortingnetwork;

<span class="dt">int</span> ceilLog2(<span class="dt">int</span> n)
{
    <span class="dt">int</span> i;
    <span class="kw">if</span> ((n &amp; (n-<span class="dv">1</span>)) == <span class="dv">0</span>) i = -<span class="dv">1</span>;
    <span class="kw">while</span> (n &gt; <span class="dv">0</span>) { ++i; n/= <span class="dv">2</span>;}
    <span class="kw">return</span> i;
}

<span class="co">/**</span>
<span class="co"> * Given a length n, returns an array of indices pairs</span>
<span class="co"> * corresponding to a sorting network for length n.</span>
<span class="co"> * Looks a bit like C code, isn&#39;t it?</span>
<span class="co"> */</span>
<span class="dt">int</span>[<span class="dv">2</span>][] sortingNetwork(<span class="dt">int</span> n)
{
    <span class="dt">int</span>[<span class="dv">2</span>][] network;
    <span class="kw">auto</span> t = ceilLog2(n);
    <span class="kw">auto</span> p = <span class="dv">1</span> &lt;&lt; (t-<span class="dv">1</span>);
    <span class="kw">while</span> (p &gt; <span class="dv">0</span>)
    {
        <span class="kw">auto</span> q = <span class="dv">1</span> &lt;&lt; (t-<span class="dv">1</span>);
        <span class="kw">auto</span> r = <span class="dv">0</span>;
        <span class="kw">auto</span> d = p;
        <span class="kw">while</span> (d &gt; <span class="dv">0</span>)
        {
            <span class="kw">for</span>(<span class="dt">int</span> i = <span class="dv">0</span>; i&lt;=(n-d-<span class="dv">1</span>); ++i)
            {
                <span class="kw">if</span> (r == (i &amp; p)) network ~= [i, i+d];
            }
            d = q-p;
            q /= <span class="dv">2</span>;
            r = p;
        }
        p /= <span class="dv">2</span>;
    }
    <span class="kw">return</span> network;
}</code></pre>
<p><code class="sourceCode d">sortingNetwork</code> returns an array of indices pairs. From this, it's easy to generate code. The basic building block done by <code class="sourceCode d">interpolate</code> (see <a href="#simple-string-interpolation">Simple String Interpolation</a>):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> buildsortingcode;
<span class="kw">import</span> stringinterpolation;
<span class="kw">import</span> sortingnetwork;

<span class="dt">string</span> buildSortingCode(<span class="dt">size_t</span> l)()
{
    <span class="kw">enum</span> network = sortingNetwork!(l);
    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(elem; network) result ~=
        interpolate!(
        <span class="st">&quot;t1 = input[#0];</span>
<span class="st">         t2 = input[#1];</span>
<span class="st">         if (!binaryFun!pred(t1, t2))</span>
<span class="st">         {</span>
<span class="st">             auto temp = t2;</span>
<span class="st">             input[#1] = t1;</span>
<span class="st">             input[#0] = temp;</span>
<span class="st">         }\n&quot;</span>)(elem[<span class="dv">0</span>], elem[<span class="dv">1</span>]);
    <span class="kw">return</span> result;
}</code></pre>
<p>And from there, I want a template that pre-generates a templated sorting network function. As for <a href="http://dlang.org/phobos/std_algorithm.html#sort">std.algorithm.sort</a>, a predicate <code class="sourceCode d">pred</code> determines the way individual range elements are compared.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> networksort;
<span class="kw">import</span> std.range;
<span class="kw">import</span> std.functional;
<span class="kw">import</span> std.exception;
<span class="kw">import</span> buildsortingcode;
<span class="kw">import</span> stringinterpolation;

<span class="kw">template</span> networkSort(<span class="dt">size_t</span> l)
{
    <span class="kw">mixin</span>(
interpolate!(
    <span class="st">&quot;void networkSort(alias pred = \&quot;a &lt; b\&quot;, R)(ref R input)</span>
<span class="st">     if (isRandomAccessRange!R)</span>
<span class="st">     {</span>
<span class="st">         enforce(input.length &gt;= #,</span>
<span class="st">                 \&quot;Calling networkSort!# with a range of less than # elements\&quot;);</span>
<span class="st">          ElementType!R t1, t2;&quot;</span>)(l)
      ~ buildSortingCode!(l)
 ~ <span class="st">&quot;}&quot;</span>);
}</code></pre>
<p>The strange mixin-in-a-template construction is there to cut the template in two, to allow user code like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// somewhere in your code</span>
<span class="kw">alias</span> networkSort!<span class="dv">32</span> sort32;

<span class="co">// somewhere else</span>
sort32(myArr);
sort32!<span class="st">&quot;a &gt; b&quot;</span>(myArr);</code></pre>
<p><code class="sourceCode d">sort32</code> is designed to work on 32-elements-long random-access ranges, without knowing in advance the nature of the range nor the predicate used to sort. If you call it on ranges with a length greater than 32, it will sort only the first 32 elements. For less than 32 elements, the enforcement will fail.</p>
<p>So, what does that little sorting routine buy us? It appears to be quite efficient for small-size arrays, compared to <a href="http://dlang.org/phobos/std_algorithm.html#sort">std.algorithm.sort</a>, but sees its performance degrade after a point. The following table compares one million sorting of <span class="math"><em>n</em></span>-elements randomly-shuffled arrays done with <code class="sourceCode d">networkSort</code> and <code class="sourceCode d">std.algorithm.<span class="dt">sort</span></code> and gives the ratio of speed-up brought by pre-computing the sorting code.</p>
<table>
<caption>Comparing <code>networkSort</code> and <code>std.algorithm.sort</code></caption>
<thead>
<tr class="header">
<th align="left">n</th>
<th align="left">Sorting network (ms)</th>
<th align="left">Standard sort (ms)</th>
<th align="left">ratio</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">5</td>
<td align="left">324</td>
<td align="left">532</td>
<td align="left">1.642</td>
</tr>
<tr class="even">
<td align="left">10</td>
<td align="left">555</td>
<td align="left">1096</td>
<td align="left">1.975</td>
</tr>
<tr class="odd">
<td align="left">10</td>
<td align="left">803</td>
<td align="left">1679</td>
<td align="left">2.091</td>
</tr>
<tr class="even">
<td align="left">20</td>
<td align="left">1154</td>
<td align="left">2314</td>
<td align="left">2.005</td>
</tr>
<tr class="odd">
<td align="left">25</td>
<td align="left">1538</td>
<td align="left">3244</td>
<td align="left">2.109</td>
</tr>
<tr class="even">
<td align="left">30</td>
<td align="left">2173</td>
<td align="left">3508</td>
<td align="left">1.614</td>
</tr>
<tr class="odd">
<td align="left">35</td>
<td align="left">4075</td>
<td align="left">4120</td>
<td align="left">1.011</td>
</tr>
<tr class="even">
<td align="left">40</td>
<td align="left">5918</td>
<td align="left">5269</td>
<td align="left">0.890</td>
</tr>
<tr class="odd">
<td align="left">45</td>
<td align="left">7479</td>
<td align="left">5959</td>
<td align="left">0.797</td>
</tr>
<tr class="even">
<td align="left">50</td>
<td align="left">9179</td>
<td align="left">6435</td>
<td align="left">0.701</td>
</tr>
</tbody>
</table>
<p>So, at least on this benchmark, <code class="sourceCode d">networkSort</code> outperforms Phobos with a speed-up of up to 100% for ranges between 5 and 40 elements.<a href="#fn12" class="footnoteRef" id="fnref12"><sup>12</sup></a> Of course, Phobos' <code class="sourceCode d">sort</code> is much more versatile, since it works on ranges with a length known only at runtime, but if you know your input's length in advance <code class="sourceCode d">networkSort</code> can be nice to use.</p>
<p>In any cases, the idea to take home away is that, if you've a good idea of what your runtime data will look like, you probably can pre-generate optimal code for it at compile time and then do some triaging at runtime.</p>
<h2 id="traits"><code>__traits</code></h2>
<p>The general <code class="sourceCode d">__traits</code> syntax can be found online <a href="www.dlang.org/traits.html">here</a>. Traits are basically another compile-time introspection tool, complementary to the <code class="sourceCode d"><span class="kw">is</span></code> expression (see <a href="#the-is-expression">the Appendix</a>). Most of time, <code class="sourceCode d">__traits</code> will return <code class="sourceCode d"><span class="kw">true</span></code> or <code class="sourceCode d"><span class="kw">false</span></code> for simple type-introspection questions (is this type or symbol an abstract class, or a final function?). As D is wont to do, these questions are sometimes ones you could ask using <code class="sourceCode d"><span class="kw">is</span></code> or template constraints, but sometimes not. What's interesting is that you can do some introspection on types, but also on symbols or expressions.</p>
<h3 id="yesno-questions-with-__traits">Yes/No Questions with <code>__traits</code></h3>
<p>Seeing how this is a document on templates and that we have already seen many introspection tools, here is a quick list of what yes/no questions you can ask which can or <em>cannot</em> be tested with <code class="sourceCode d"><span class="kw">is</span></code>:<a href="#fn13" class="footnoteRef" id="fnref13"><sup>13</sup></a></p>
<table>
<caption>Comparison between <code>__traits</code> and other introspection tools</caption>
<thead>
<tr class="header">
<th align="left">Question</th>
<th align="left">Doable with other tools?</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">isArithmetic</td>
<td align="left">Yes</td>
</tr>
<tr class="even">
<td align="left">isAssociativeArray</td>
<td align="left">Yes</td>
</tr>
<tr class="odd">
<td align="left">isFloating</td>
<td align="left">Yes</td>
</tr>
<tr class="even">
<td align="left">isIntegral</td>
<td align="left">Yes</td>
</tr>
<tr class="odd">
<td align="left">isScalar</td>
<td align="left">Yes</td>
</tr>
<tr class="even">
<td align="left">isStaticArray</td>
<td align="left">Yes</td>
</tr>
<tr class="odd">
<td align="left">isUnsigned</td>
<td align="left">Yes</td>
</tr>
<tr class="even">
<td align="left">isAbstractClass</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">isFinalClass</td>
<td align="left">No</td>
</tr>
<tr class="even">
<td align="left">isVirtualFunction</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">isAbstractFunction</td>
<td align="left">No</td>
</tr>
<tr class="even">
<td align="left">isFinalFunction</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">isStaticFunction</td>
<td align="left">No</td>
</tr>
<tr class="even">
<td align="left">isRef</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">isOut</td>
<td align="left">No</td>
</tr>
<tr class="even">
<td align="left">isLazy</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">hasMember</td>
<td align="left">No (Yes?)</td>
</tr>
<tr class="even">
<td align="left">isSame</td>
<td align="left">No</td>
</tr>
<tr class="odd">
<td align="left">compiles</td>
<td align="left">Yes (in a way)</td>
</tr>
</tbody>
</table>
<p>These can all be quite useful in your code, but I'll shy away from them since they are not heavily template-related. More interesting in my opinion is using <code class="sourceCode d">__traits</code> to get new information about a type. These are really different from other introspection tools and I will deal with them in more detail right now.</p>
<h3 id="identifier"><code>identifier</code></h3>
<p><code class="sourceCode d">identifier</code> gives you a symbol's name as a string. This is quite interesting, since some symbols are what I'd call <em>active</em>: for example, if <code class="sourceCode d">foo</code> is a function, <code class="sourceCode d">foo.<span class="dt">stringof</span></code> will try to first call <code class="sourceCode d">foo</code> and the <code class="sourceCode d">.<span class="dt">stringof</span></code> will fail. Also, <code class="sourceCode d">.<span class="dt">stringof</span></code>, though eminently useful, sometimes returns strangely formatted strings. <code class="sourceCode d">identifier</code> is much more well-behaved.</p>
<p>Let's get back to one of the very first templates in this doc, <code class="sourceCode d">nameOf</code> <a href="#template-declarations">here</a>. Initially, it was coded like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> nameOf(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> <span class="dt">string</span> name = a.<span class="dt">stringof</span>; <span class="co">// enum: manifest constant</span>
                                   <span class="co">// determined at compile-time</span>
}</code></pre>
<p>But, this fails for functions:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="dt">int</span> foo(<span class="dt">int</span> i, <span class="dt">int</span> j) { <span class="kw">return</span> i+j;}

<span class="kw">auto</span> name = nameOf!foo; <span class="co">// Error, &#39;foo&#39; must be called with 2 arguments</span></code></pre>
<p>It's much better to use <code class="sourceCode d">__traits</code> (also, <a href="#the-eponymous-trick">the eponymous trick</a>):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> nameof;

<span class="kw">template</span> nameOf(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> <span class="dt">string</span> nameOf = __traits(identifier, a);
}

<span class="kw">unittest</span>
{
    <span class="dt">int</span> foo(<span class="dt">int</span> i, <span class="dt">int</span> j) { <span class="kw">return</span> i+j;}
    <span class="kw">enum</span> name = nameOf!foo; <span class="co">// name is available at compile-time</span>

    <span class="kw">assert</span>(name == <span class="st">&quot;foo&quot;</span>);
}</code></pre>
<p>Note that this works for many (all?) kinds of symbols: template names, class names, even modules:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.typecons;
<span class="kw">import</span> nameof;

<span class="kw">enum</span> name2 = nameOf!(nameOf); <span class="co">// &quot;nameOf(alias a)&quot;</span>
<span class="kw">enum</span> name3 = nameOf!(std.typecons); <span class="co">//&quot;typecons&quot;</span></code></pre>
<h3 id="getmember"><code>getMember</code></h3>
<p>In a nutshell, <code class="sourceCode d">__traits(getMember, name, <span class="st">&quot;member&quot;</span>)</code> will give you direct access to <code class="sourceCode d">name.member</code>. This is the real member: you can get its value (if any), set it anew, etc. Any D construct with members is OK as a <code class="sourceCode d">name</code>. If you wonder why the aggregate is called directly by its own name whereas the member needs a string, it's because the aggregate is a valid symbol (it exists by itself), when the member's name has no existence outside the aggregate (or even worse, may refer to another, unrelated, construct).</p>
<blockquote>
<p><strong>Aggregates.</strong> I'll use <em>aggregate</em> as a catch-all term for any D construct that has members. Structs and classes are obvious aggregates, as are interfaces, but it's interesting to keep in mind that templates too have members (remember section <a href="#instantiating-a-template">Instantiating a Template</a>? A template is a named, parameterized scope). So all <code>__traits</code> calls shown in this section can be used on templates. That's interesting to keep in mind. Even more interesting, to my eyes, is that <em>modules</em> are also aggregates even though they are not first-class citizens in D-land. You'll see examples of this in the following sections.</p>
</blockquote>
<h3 id="allmembers"><code>allMembers</code></h3>
<p>This one is cool. Given an aggregate name, <code class="sourceCode d">__traits(allMembers, aggregate)</code> will return a tuple of string literals, each of which is the name of a member. For a class, the parent classes' members are also included. Built-in properties (like <code class="sourceCode d">.<span class="dt">sizeof</span></code>) are not included in that list. Note that I did say 'tuple': it's a bit more powerful than an array, because it can be iterated over at compile-time.</p>
<p>The names are not repeated for overloads, but see the next section for a way to get the overloads.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingallmembers1;

<span class="kw">class</span> MyClass
{
    <span class="dt">int</span> i;

    <span class="kw">this</span>() { i = <span class="dv">0</span>;}
    <span class="kw">this</span>(<span class="dt">int</span> j) { i = j;}
    ~<span class="kw">this</span>() { }

    <span class="dt">void</span> foo() { ++i;}
    <span class="dt">int</span> foo(<span class="dt">int</span> j) { <span class="kw">return</span> i+j;}
}

<span class="dt">void</span> main()
{
    <span class="co">// Put in an array for a more human-readable printing</span>
    <span class="kw">enum</span> myMembers = [__traits(allMembers, MyClass)];

    <span class="co">// See &quot;i&quot; and &quot;foo&quot; in the middle of standard class members</span>
    <span class="co">// &quot;foo&quot; appears only once, despite it being overloaded.</span>
    <span class="kw">assert</span>(myMembers == [<span class="st">&quot;i&quot;</span>, <span class="st">&quot;__ctor&quot;</span>, <span class="st">&quot;__dtor&quot;</span>, <span class="st">&quot;foo&quot;</span>, <span class="st">&quot;toString&quot;</span>,
                         <span class="st">&quot;toHash&quot;</span>, <span class="st">&quot;opCmp&quot;</span>, <span class="st">&quot;opEquals&quot;</span>, <span class="st">&quot;Monitor&quot;</span>, <span class="st">&quot;factory&quot;</span>]);
}</code></pre>
<p>So the above code is a nice way to get members, both fields (like <code>i</code>) and methods (like <code class="sourceCode d">foo</code>). In case you wonder what <code class="sourceCode d"><span class="st">&quot;__ctor&quot;</span></code> and <code class="sourceCode d"><span class="st">&quot;__dtor&quot;</span></code> are, it's the internal D name for constructors and destructors. But it's perfectly usable in your code! For structs, the list far less cluttered since they only get the constructor and destructor's names and <code class="sourceCode d">opAssign</code>, the assignment operator (<code>=</code>).</p>
<p>Since this trait returns strings, it can be plugged directly into <code class="sourceCode d">getMember</code>. See a bit farther down a way to get a nice list of all members and their types.</p>
<p>Now, let's ramp things up a bit: what about class and struct templates? Let's try this out:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> allmemberstemplate;

<span class="kw">class</span> MyClass(T)
{
    T field;
}

<span class="kw">static</span> <span class="kw">assert</span>([__traits(allMembers, MyClass)] == [<span class="st">&quot;MyClass&quot;</span>]);</code></pre>
<p>Oh, what happened? Remember from <a href="#basics">Basics</a> that struct, classes and functions templates are just syntactic sugar for the 'real' syntax:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> MyClass(T)
{
    <span class="kw">class</span> MyClass
    {
        T field;
    }
}</code></pre>
<p>So, <code class="sourceCode d">MyClass</code> is just the name of the external template, whose one and only member is the <code class="sourceCode d">MyClass</code> class. So all is well. If you instantiate the template, it functions as you might expect:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> allmemberstemplate2;
<span class="kw">import</span> allmemberstemplate;

<span class="kw">static</span> <span class="kw">assert</span>([__traits(allMembers, MyClass!<span class="dt">int</span>)]
           == [<span class="st">&quot;field&quot;</span>, <span class="st">&quot;toString&quot;</span>, <span class="st">&quot;toHash&quot;</span>, <span class="st">&quot;opCmp&quot;</span>,
               <span class="st">&quot;opEquals&quot;</span>, <span class="st">&quot;Monitor&quot;</span>, <span class="st">&quot;factory&quot;</span>]);</code></pre>
<p>If you remember one of the very first uses we saw for templates in <a href="#instantiating-a-template">Instantiating a Template</a>, that is as a named, parameterized scope, this can give rise to interesting introspection:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> templateintrospection;

<span class="kw">template</span> Temp(A, B)
{
    A a;
    B foo(A a, B b) { <span class="kw">return</span> b;}
    <span class="dt">int</span> i;
    <span class="kw">alias</span> A    AType;
    <span class="kw">alias</span> A[B] AAType;
}

<span class="kw">static</span> <span class="kw">assert</span>([__traits(allMembers, Temp)]
           == [<span class="st">&quot;a&quot;</span>, <span class="st">&quot;foo&quot;</span>, <span class="st">&quot;i&quot;</span>, <span class="st">&quot;AType&quot;</span>, <span class="st">&quot;AAType&quot;</span>]);
<span class="kw">static</span> <span class="kw">assert</span>([__traits(allMembers, Temp!(<span class="dt">double</span>,<span class="dt">string</span>))]
           == [<span class="st">&quot;a&quot;</span>,<span class="st">&quot;foo&quot;</span>, <span class="st">&quot;i&quot;</span>, <span class="st">&quot;AType&quot;</span>, <span class="st">&quot;AAType&quot;</span>]);</code></pre>
<p>As you can see, you also get aliases' names. By the way, this is true for structs and templates also.</p>
<p>Another fun fact is that D modules are amenable to <code class="sourceCode d">__traits</code>'s calls, though that's true only for packaged modules (that is, <code class="sourceCode d"><span class="kw">import</span> pack.mod;</code> imports the <code class="sourceCode d">pack</code> and <code class="sourceCode d">mod</code> symbols, but <code class="sourceCode d"><span class="kw">import</span> mod;</code> imports nothing).</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> allmembersmodule;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.compiler;

<span class="co">// Huuuge list of names</span>
<span class="kw">enum</span> algos = [__traits(allMembers, std.algorithm)];
<span class="co">// A bit shorter</span>
<span class="kw">enum</span> compiler = [__traits(allMembers, std.compiler)];

<span class="dt">void</span> main()
{
    <span class="kw">assert</span>(compiler == [<span class="st">&quot;object&quot;</span>, <span class="st">&quot;name&quot;</span>,
                        <span class="st">&quot;Vendor&quot;</span>, <span class="st">&quot;vendor&quot;</span>,
                        <span class="st">&quot;version_major&quot;</span>, <span class="st">&quot;version_minor&quot;</span>,
                        <span class="st">&quot;D_major&quot;</span>, <span class="st">&quot;D_minor&quot;</span>]);
}</code></pre>
<p>In the previous code, you see that among <code>a</code> members, there is <code class="sourceCode d"><span class="st">&quot;object&quot;</span></code> (the implicit <code class="sourceCode d">object.d</code> module module} imported by the runtime), and <code class="sourceCode d"><span class="st">&quot;std&quot;</span></code>, the global package that shows here whenever you import a <code class="sourceCode d">std.*</code> module. It would be easy to imagine a template that recursively explores the members, finds the modules and tries to recurse into them to get a complete import-tree with a template. Alas, <code class="sourceCode d"><span class="st">&quot;std&quot;</span></code> blocks that, since the package itself does not have a member.<a href="#fn14" class="footnoteRef" id="fnref14"><sup>14</sup></a></p>
<blockquote>
<p><strong>introspection.</strong> I'm pretty sure auto-introspection (a module calling <code>allMembers</code> on its own name) used to work in Fall 2011. Now it's 2012 and this doesn't work anymore. Hmmm.</p>
</blockquote>
<p>Like for the other aggregates, you get the aliased names also, and the unit tests defined in the module.<a href="#fn15" class="footnoteRef" id="fnref15"><sup>15</sup></a> <a href="#fn16" class="footnoteRef" id="fnref16"><sup>16</sup></a></p>
<blockquote>
<p><strong>What's the point of inspecting a module?</strong> Well, first that was just for fun and to see if I could duplicate a module or create a struct with an equivalent members list (all forwarding to the module's own members). But the real deal for me was when using string mixins to generate some type. If the user uses the mixin in its own module, it could create conflicts with already-existing names. So I searched for a way for a mixin template to inspect the module it's currently being instantiated in. Then, I wanted to write a template that, given a class name, would give me the entire hierarchy it's in (as the local module scope would see it, that was enough for me). This <code class="sourceCode d">Hierarchy</code> template should be shown in this document. Then, while testing <a href="http://dlang.org/phobos/std_traits.html#ParameterTypeTuple">std.traits.ParameterTypeTuple</a>, I saw that it gives the parameter typetuple of <em>one</em> function, even when it's overloaded. So inspecting a module is also a way to get the full list of functions with a particular name and getting the parameter typetuple for each of them.</p>
</blockquote>
<blockquote>
<p><strong>TODO</strong> Inject Hierarchy here. <strong>TODO</strong> Code a more powerful version of ParameterTypeTuple.</p>
</blockquote>
<h3 id="derivedmembers"><code>derivedMembers</code></h3>
<p>Really it's the same as above, except that you do not get a class' parents members, only the class' own members.</p>
<h3 id="getoverloads"><code>getOverloads</code></h3>
<p>Given:</p>
<ul>
<li>an aggregate name or an instance of that agregrate</li>
<li>a member name as a string</li>
</ul>
<p>Then, <code class="sourceCode d">__traits(getOverloads, name, <span class="st">&quot;member&quot;</span>)</code> will give you a tuple of all local overloads of <code class="sourceCode d">name.member</code>. By 'local', I mean that for classes, you do not get the parents classes overloads. There is a difference between using <code class="sourceCode d">getOverloads</code> on a type and on an instance: in the former case, you get a tuple of all the overloads. What's cool is that, by using <code class="sourceCode d"><span class="st">&quot;__ctor&quot;</span></code>, you also get a direct access to a type's constructor overloads. That can be quite handy in some cases.</p>
<h3 id="getting-all-members-even-overloaded-ones">Getting All Members, Even Overloaded Ones</h3>
<p>Now, if you're like me, the urge to mix <code class="sourceCode d">allMembers</code> (which returns the members' names without overloads) and <code class="sourceCode d">getOverloads</code> (which returns the overload of <em>one</em> member) is quite great. So let's do that.</p>
<p>First, a bit of machinery: I want the members to be described by a name and a type. Let's create a struct holder, templated of course:</p>
<blockquote>
<p><strong>TODO</strong> Getting qualified names would be better.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> member;

<span class="kw">struct</span> Member(<span class="dt">string</span> n, T)
{
    <span class="kw">enum</span> name = n; <span class="co">// for external access</span>
    <span class="kw">alias</span> T Type;
}</code></pre>
<p>Given a member name, we'll need a template that delivers the associated <code class="sourceCode d">Member</code>. I also want a way to impose the name, this will come handy later on:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> makemember;
<span class="kw">public</span> <span class="kw">import</span> member;
<span class="kw">import</span> nameof;

<span class="kw">template</span> MakeMember(<span class="kw">alias</span> member)
{
    <span class="kw">mixin</span>( <span class="st">&quot;alias Member!(\&quot;&quot;</span>
         ~ nameOf!member
         ~ <span class="st">&quot;\&quot;, typeof(member)) MakeMember;&quot;</span>);
}

<span class="kw">template</span> MakeNamedMember(<span class="dt">string</span> name)
{
    <span class="kw">template</span> MakeNamedMember(<span class="kw">alias</span> member)
    {
        <span class="kw">mixin</span>( <span class="st">&quot;alias Member!(\&quot;&quot;</span>
             ~ name
             ~ <span class="st">&quot;\&quot;, typeof(member)) MakeNamedMember;&quot;</span>);
    }
}</code></pre>
<p>Now, given an aggregate name and a member name (as a string, since these do not exist by themselves), we want a list of <code class="sourceCode d">Member</code> structs holding all the information:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> overloads1;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> makemember;

<span class="kw">template</span> Overloads(<span class="kw">alias</span> a, <span class="dt">string</span> member)
{
    <span class="kw">alias</span> staticMap!(MakeMember, __traits(getOverloads,a, member))
          Overloads;
}</code></pre>
<p><code class="sourceCode d">staticMap</code> is explained in section <a href="#mapping-on-type-tuples">Mapping on Type Tuples</a>.</p>
<p>Now, that already works:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> myclass;

<span class="kw">class</span> MyClass
{
    <span class="dt">int</span> i; <span class="co">// field</span>
    <span class="kw">alias</span> i j; <span class="co">// symbol alias</span>

    <span class="kw">alias</span> <span class="dt">int</span> Int; <span class="co">// type alias</span>

    <span class="kw">struct</span> Inner {} <span class="co">// Inner type</span>

    <span class="kw">template</span> Temp(T) { <span class="kw">alias</span> T Temp;} <span class="co">// template</span>

    <span class="kw">this</span>() { i = <span class="dv">0</span>;} <span class="co">// constructor #1</span>
    <span class="kw">this</span>(<span class="dt">int</span> j) { i = j;} <span class="co">// constructor #2</span>
    ~<span class="kw">this</span>() { }

    <span class="dt">void</span> foo(<span class="dt">int</span> j) { ++i;} <span class="co">// foo overload #1</span>
    <span class="dt">int</span> foo(<span class="dt">int</span> j, <span class="dt">int</span> k = <span class="dv">0</span>) { <span class="kw">return</span> i+j;} <span class="co">// foo overload #2</span>

    <span class="kw">alias</span> foo bar; <span class="co">// symbol alias</span>

    <span class="kw">unittest</span>
    {
        <span class="dt">int</span> i;
    }
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingoverloads1;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> overloads1;
<span class="kw">import</span> myclass;

<span class="dt">void</span> main()
{
    <span class="kw">alias</span> Overloads!(MyClass, <span class="st">&quot;foo&quot;</span>) o;

    <span class="co">/*</span>
<span class="co">    prints:</span>
<span class="co">    foo, of type: void(int j)</span>
<span class="co">    foo, of type: int(int j, int k = 0)</span>
<span class="co">    */</span>
    <span class="kw">foreach</span>(elem; o)
        writeln(elem.name, <span class="st">&quot;, of type: &quot;</span>, elem.Type.<span class="dt">stringof</span>);
}</code></pre>
<p>We indeed got two <code class="sourceCode d">Member</code> instances, one for each overload. Each <code class="sourceCode d">Member</code> holds the name <code class="sourceCode d"><span class="st">&quot;foo&quot;</span></code> and the overload type. Except, there is a catch: for a field, there are no overloads. Aliases are also problematic and not correctly dealt with. We need to pay attention to that in <code class="sourceCode d">Overloads</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> overloads2;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> makemember;

<span class="co">/**</span>
<span class="co"> * Gets the overloads of a given member, as a Member type tuple.</span>
<span class="co"> */</span>
<span class="kw">template</span> Overloads(<span class="kw">alias</span> a, <span class="dt">string</span> member)
{
    <span class="co">// a.member is a method</span>
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, __traits(getOverloads, a, member))
        &amp;&amp; __traits(getOverloads, a, member).<span class="dt">length</span> &gt; <span class="dv">0</span>)
        <span class="kw">alias</span> staticMap!(MakeNamedMember!(member), __traits(getOverloads, a, member))
              Overloads;
    <span class="kw">else</span> <span class="co">// field or alias</span>
    <span class="co">// a.member is a field, or a symbol alias</span>
        <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(<span class="dt">typeof</span>(__traits(getMember, a, member))))
            <span class="kw">mixin</span>( <span class="st">&quot;alias Member!(\&quot;&quot;</span>
                 ~ member
                 ~ <span class="st">&quot;\&quot;, typeof(__traits(getMember, a, member))) Overloads;&quot;</span>);
    <span class="co">// a.member is a type alias</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">mixin</span>( <span class="st">&quot;is(Member!(\&quot;&quot;</span>
                         ~ member
                         ~ <span class="st">&quot;\&quot;, __traits(getMember, a, member)))&quot;</span>))
        <span class="kw">mixin</span>( <span class="st">&quot;alias Member!(\&quot;&quot;</span>
             ~ member
             ~ <span class="st">&quot;\&quot;, __traits(getMember, a, member)) Overloads;&quot;</span>);
    <span class="co">// a.member is template</span>
    <span class="kw">else</span>
        <span class="kw">mixin</span>( <span class="st">&quot;alias Member!(\&quot;&quot;</span>
             ~ member
             ~ <span class="st">&quot;\&quot;, void) Overloads;&quot;</span>);
}</code></pre>
<p>The entire template may be a bit daunting, but it's to give it a (mostly) correct way to deal with the many kinds of member an aggregate may have: fields, methods, type aliases, symbols aliases, template names. As of this writing, it does not deal correctly with inner types: I think it should give them a <code class="sourceCode d">Outer.Inner</code> type, whereas here it produces only <code class="sourceCode d">Inner</code>.<a href="#fn17" class="footnoteRef" id="fnref17"><sup>17</sup></a> Also, unittest blocks appear, but they are given a <code class="sourceCode d"><span class="dt">void</span></code> type, the default case in this template. I think they should have a <code class="sourceCode d"><span class="dt">void</span>()</code> type.</p>
<p>The last step is to get this for all members of a given aggregate. It's quite easy:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> allmembers;
<span class="kw">import</span> overloads2;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> GetOverloads(<span class="kw">alias</span> a)
{
    <span class="kw">template</span> GetOverloads(<span class="dt">string</span> member)
    {
        <span class="kw">alias</span> Overloads!(a, member) GetOverloads;
    }
}

<span class="kw">template</span> AllMembers(<span class="kw">alias</span> a)
{
    <span class="kw">alias</span> staticMap!(GetOverloads!(a), __traits(allMembers, a)) AllMembers;
}</code></pre></td></tr></table>
<p>The strange <code class="sourceCode d">GetOverloads</code> two-stage construction is just a way to map it more easily on line 15. So, this was quite long to explain, but it works nicely:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingallmembers2;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> myclass;
<span class="kw">import</span> allmembers;

<span class="dt">void</span> main()
{
    <span class="kw">alias</span> AllMembers!(MyClass) O;
    writeln(O.<span class="dt">stringof</span>);

    <span class="kw">foreach</span>(o; O)
        writeln(o.name, <span class="st">&quot;, of type: &quot;</span> ~ o.Type.<span class="dt">stringof</span>);

    <span class="co">/*</span>
<span class="co">    prints:</span>
<span class="co">    i, of type: int</span>
<span class="co">    j, of type: int</span>
<span class="co">    Int, of type: int</span>
<span class="co">    (...)</span>
<span class="co">    __ctor, of type: MyClass()</span>
<span class="co">    __ctor, of type: MyClass(int j)</span>
<span class="co">    (...)</span>
<span class="co">    foo, of type: void(int j)</span>
<span class="co">    foo, of type: int(int j, int k = 0)</span>
<span class="co">    (...)</span>
<span class="co">    */</span>
}</code></pre>
<p>That's cool, every member and overload is accounted for: the two contructors are there, the destructor also, and of course <code>i</code>, of type <code class="sourceCode d"><span class="dt">int</span></code>.</p>
<blockquote>
<p><strong>TODO</strong> Example: store all members in a hashtable or a polymorphic association list. As a mixin, to be put inside types to enable runtime reflection? <code class="sourceCode d">(a.send(<span class="st">&quot;someMethod&quot;</span>, args), a.setInstanceVariable(<span class="st">&quot;i&quot;</span>,<span class="dv">5</span>))</code></p>
</blockquote>
<h3 id="testing-for-interface-implementation">Testing for Interface Implementation</h3>
<p>The previous section gave us a way to get an aggregate member list. From there, it's an easy step to get an interface's member list and to see if a given symbol's members contains the entire interface member list:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> implements;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> allmembers;

<span class="co">/**</span>
<span class="co"> * Statically check if symbol &#39;a&#39; implements interface I</span>
<span class="co"> * (that is, if all members of I are found in members of a.</span>
<span class="co"> */</span>
<span class="kw">template</span> implements(<span class="kw">alias</span> a, I) <span class="kw">if</span> (<span class="kw">is</span>(I == <span class="kw">interface</span>))
{
    <span class="kw">alias</span> implementsImpl!(a, AllMembers!I) implements;
}

<span class="kw">template</span> implementsImpl(<span class="kw">alias</span> a, Items...)
{
    <span class="kw">static</span> <span class="kw">if</span> (Items.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">enum</span> implementsImpl = <span class="kw">true</span>;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (staticIndexOf!(Items[<span class="dv">0</span>], AllMembers!a) == -<span class="dv">1</span>)
        <span class="kw">enum</span> implementsImpl = <span class="kw">false</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> implementsImpl = implementsImpl!(a, Items[<span class="dv">1</span>..$]);
}

<span class="kw">interface</span> I
{
    <span class="dt">int</span> foo(<span class="dt">int</span> i);
    <span class="dt">void</span> foo();

    <span class="dt">string</span> toString();
}

<span class="kw">class</span> Bad
{
    <span class="dt">void</span> foo(<span class="dt">int</span> i) {}
}

<span class="kw">struct</span> Good
{
    <span class="dt">int</span> field;

    <span class="dt">int</span> foo(<span class="dt">int</span> i) { <span class="kw">return</span> i;}
    <span class="dt">void</span> foo() { field = <span class="dv">1</span>;}

    <span class="dt">string</span> toString() { <span class="kw">return</span> <span class="st">&quot;I&#39;m a good struct!&quot;</span>;}
}

<span class="kw">unittest</span>
{
    <span class="kw">assert</span>( implements!(Good, I));
    <span class="kw">assert</span>(!implements!(Bad, I));
}</code></pre>
<h3 id="getvirtualfunctions"><code>getVirtualFunctions</code></h3>
<p>It's in the same family than <code class="sourceCode d">getOverloads</code> and such. It'll give you the list of virtual overloads for a class method. Given a class name, finding all overloads of all fields, even overriden ones, is let as a exercise to the reader.</p>
<h3 id="parent"><code>parent</code></h3>
<p><code class="sourceCode d">__traits(parent, symbol)</code> will return the symbol that's the parent of it. It's <em>not</em> the parent in a 'class hierarchy' sense,<a href="#fn18" class="footnoteRef" id="fnref18"><sup>18</sup></a> it deals with qualified names and strip one level. Once you reach the toplevel scope, it returns the module name (this can be dangerous, because modules themselves do not have parents). See:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> cclass;
<span class="kw">import</span> nameof;

<span class="kw">class</span> C
{
    <span class="dt">int</span> i;
    <span class="dt">int</span> foo(<span class="dt">int</span> j)
    {
        <span class="dt">int</span> k; <span class="co">// k is &quot;cclass.C.foo.k&quot;</span>
        <span class="kw">assert</span>(nameOf!(__traits(parent, k)) == <span class="st">&quot;foo&quot;</span>);
        <span class="kw">return</span> i+k;
    }
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> parent;
<span class="kw">import</span> nameof;
<span class="kw">import</span> cclass;

<span class="co">// C is more precisely a cclass.C)</span>
<span class="kw">static</span> <span class="kw">assert</span>(nameOf!(__traits(parent, C)) == <span class="st">&quot;cclass&quot;</span>);

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> c = <span class="kw">new</span> C(); <span class="co">// c is &quot;parent.main.c&quot;</span>
    <span class="kw">assert</span>(nameOf!(__traits(parent, c)) == <span class="st">&quot;main&quot;</span>);
    <span class="kw">assert</span>(nameOf!(__traits(parent, c.i)) == <span class="st">&quot;C&quot;</span>);
    c.foo(<span class="dv">1</span>);
}</code></pre>
<p>Even if there is no <code class="sourceCode d">qualifiedIdentifier</code> in <code class="sourceCode d">__traits</code>, we can construct a template to get it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> qualifiedname;
<span class="kw">import</span> nameof;

<span class="kw">template</span> qualifiedName(<span class="kw">alias</span> a)
{
    <span class="co">// does it have a parent?</span>
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, __traits(parent, a)))
    <span class="co">// If yes, get the name and recurse</span>
        <span class="kw">enum</span> qualifiedName = qualifiedName!(__traits(parent, a))
                           ~  <span class="st">&quot;.&quot;</span> ~ nameOf!(a);
    <span class="co">// if not, it&#39;s a module name. Stop there.</span>
    <span class="kw">else</span>
        <span class="kw">enum</span> qualifiedName = nameOf!a;
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingqualifiedname;
<span class="kw">import</span> qualifiedname;
<span class="kw">import</span> cclass;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> c = <span class="kw">new</span> C();
    <span class="kw">assert</span>(qualifiedName!c == <span class="st">&quot;usingqualifiedname.main.c&quot;</span>);

    <span class="kw">assert</span>(qualifiedName!(c.foo) == <span class="st">&quot;cclass.C.foo&quot;</span>); <span class="co">// same in both cases</span>
    <span class="kw">assert</span>(qualifiedName!(C.foo) == <span class="st">&quot;cclass.C.foo&quot;</span>);
}</code></pre>
<p>Note that <code class="sourceCode d">c.foo</code> is <em>not</em> qualified as <code class="sourceCode d">usingqualifiedname.main.c.foo</code>.</p>
<h3 id="local-scope-name">Local Scope Name</h3>
<p>Sometimes, when dealing with <a href="#mixin-templates">mixin templates</a> or <a href="#string-mixins">string mixins</a>, you'll inject code in an unknown scope. To get your way round, it can be useful to get the local scope's name. Intuitively, the previous example could help with that: just create a local variable, get the qualified name of its parent to determine in which scope the mixin is. Then, expose the scope name. Let's call this one <code class="sourceCode d">scopeName</code> and the associated inquisitive template <code class="sourceCode d">getScopeName</code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> scopename;
<span class="kw">public</span> <span class="kw">import</span> qualifiedname;

<span class="kw">mixin</span> <span class="kw">template</span> getScopeName()
{
    <span class="kw">enum</span> scopeName = qualifiedName!(__traits(parent, scopeName));
}</code></pre>
<p>The idea is to declare local enum called <code class="sourceCode d">scopeName</code> and take the qualified name of its own parent in the same expression (yes, that works!).</p>
<p>To use <code class="sourceCode d">getScopeName</code>, just mix it in where you need a local scope name:</p>
<p><em>BUG</em>: Something changed since I last tested this code (2012). As of now (DMD 2.066, August 2014), this does not work anymore. I'll add it to my TODO list.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingscopename;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> scopename;

<span class="kw">class</span> C
{
    <span class="kw">mixin</span> getScopeName; <span class="co">// 1</span>

    <span class="dt">int</span> i;
    <span class="dt">int</span> foo(<span class="dt">int</span> j)
    {
        <span class="dt">int</span> k;
        <span class="kw">mixin</span> getScopeName; <span class="co">// 2</span>
        writeln(scopeName);
        <span class="kw">return</span> i+k;
    }
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> c = <span class="kw">new</span> C();
    writeln(c.scopeName); <span class="co">// &quot;test.C&quot; (1)</span>
    c.foo(<span class="dv">1</span>);             <span class="co">// &quot;test.C.foo&quot; (2)</span>

    <span class="kw">mixin</span> getScopeName; <span class="co">// 3</span>
    writeln(scopeName); <span class="co">// &quot;test.main&quot; (3)</span>
}</code></pre>
<h2 id="wrapping-it-all-together">Wrapping it all Together</h2>
<blockquote>
<p><strong>Unfinished</strong> I have to dig some cute examples in my code base. Using string mixins and CTFE and templates all together.</p>
</blockquote>
<h1 id="examples">Examples</h1>
<p>This part will present various examples showing what can be done with D templates, be it type manipulation, code generation or language extension Most examples are code snippets that were useful to me at one time or another. I hope they will be useful to you too.</p>
<blockquote>
<p><strong>Contributors welcome!</strong> Even more than for other parts, I welcome any short and synthetic example of what can be done with templates. Do not hesitate to chime in and push some code in this doc!</p>
</blockquote>
<h2 id="type-sorcery">Type Sorcery</h2>
<p>One of the most fundamental use of templates is type sorcery: type creation, type manipulation, etc. D being a statically type language, all of your creations will have a defined type. Sometimes, these can be cumbersome to write or manipulate. Templates can help you in this.</p>
<h3 id="mapping-filtering-and-folding-types">Mapping, Filtering and Folding Types</h3>
<p>As we saw in section <a href="#template-tuple-parameters">Template Tuple Parameters</a>, template tuple parameters can hold type tuples (that's even their original role). Since these can be iterated, indexed or sliced, they are ideal candidates to some standard iteration algorithms. As for ranges, you can map another template on type tuples, filter the types you want to extract or fold (reduce) them into another type.</p>
<blockquote>
<p><strong>And non-types?</strong> What about acting on expression tuples? You can do that too. Even though this section is called <em>Type</em> Sorcery, all templates here can work on expression tuples too. Do not feel limited.</p>
</blockquote>
<h4 id="mapping-on-type-tuples">Mapping on Type Tuples</h4>
<p>Mapping a type tuple is simply applying another (unary) template on all types of a type tuple. Phobos already defines <code class="sourceCode d">staticMap</code> in <a href="http://dlang.org/phobos/std_typetuple.html">std.typetuple</a>, but it's a nice exercise to code it again. We want a template that takes another template name (as an <code class="sourceCode d"><span class="kw">alias</span></code> parameter), say <code class="sourceCode d">Wrapper</code>, and a typetuple (<code class="sourceCode d">T0, T1, T2, ..., Tn</code>) and returns <code class="sourceCode d">Wrapper!T0, Wrapper!T1, Wrapper!T2, ..., Wrapper!Tn</code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> staticmap;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> staticMap(<span class="kw">alias</span> M, T...)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// End of sequence</span>
        <span class="kw">alias</span> TypeTuple!() staticMap; <span class="co">// stop there</span>
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(M!(T[<span class="dv">0</span>]), staticMap!(M, T[<span class="dv">1</span>..$])) staticMap;
}</code></pre>
<p>We use the auto-flattening of type tuples to aggregate the results into a unique tuple. Notice how indexing and slicing make for a not-so-complicated piece of code. As it's already defined in <a href="http://dlang.org/phobos/std_typetuple.html">std.typetuple</a>, I'll use Phobos' template from now on.</p>
<p>Even a simple template such as this one can have great uses:</p>
<ul>
<li>Getting rid of all qualifiers in a type list, by mapping <a href="http://dlang.org/phobos/std_traits.html#Unqual">std.traits.Unqual</a> on the types.</li>
<li>Generating a huge quantity of types by using a typetuple-returning mapper (see below).</li>
<li>Given a bunch of function types, getting their return types or parameter typetuples.</li>
</ul>
<h4 id="example-testing-a-function">Example: Testing a Function</h4>
<p>The seconde use in the previous section's list can be useful to unit-test a part of your code. Suppose you have a templated function that is supposed to work on any built-in type. You do not need to generate all possible combinations of types. Just use <code class="sourceCode d">staticMap</code> to generate them for you:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> qualified;
<span class="kw">import</span> std.typetuple;

<span class="co">/**</span>
<span class="co">* Given a type T, generates all qualified versions of T</span>
<span class="co">* that you find interesting (eleven versions all in all).</span>
<span class="co">*/</span>
<span class="kw">template</span> Qualified(T)
{
    <span class="kw">alias</span> TypeTuple!(
                     T, <span class="kw">const</span>(T), <span class="kw">immutable</span>(T), shared(T),
                     T[],<span class="kw">const</span>(T)[],<span class="kw">immutable</span>(T)[], shared(T)[],
                     <span class="kw">const</span>(T[]), <span class="kw">immutable</span>(T[]), shared(T[])
                    ) Qualified;
}

<span class="co">// All 16 built-in types you&#39;re interested in.</span>
<span class="kw">alias</span> TypeTuple!(
                 <span class="dt">bool</span>,
                 <span class="dt">ubyte</span>,<span class="dt">byte</span>,
                 <span class="dt">ushort</span>,<span class="dt">short</span>,
                 <span class="dt">uint</span>,<span class="dt">int</span>,
                 <span class="dt">ulong</span>,<span class="dt">long</span>,
                 <span class="dt">float</span>,<span class="dt">double</span>,<span class="dt">real</span>,
                 <span class="dt">char</span>,<span class="dt">wchar</span>,<span class="dt">dchar</span>
                ) ValueTypes;

<span class="co">// Bang, 11*16 types generated.</span>
<span class="kw">alias</span> staticMap!(Qualified,ValueTypes) QualifiedTypes;

<span class="co">// If you&#39;re really a pervert (note that there will be duplicates)</span>
<span class="kw">alias</span> staticMap!(Qualified, QualifiedTypes) DoublyQualifiedTypes;</code></pre>
<p>Now, if your function is supposed to work on all the generated qualified types, just test it:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> tester;
<span class="kw">import</span> qualified;

<span class="dt">void</span> myFun(T)(T t) {}

<span class="kw">template</span> test(<span class="kw">alias</span> fun)
{
    <span class="dt">void</span> on(T...)()
    {
        <span class="kw">foreach</span>(Type; T)
            <span class="kw">static</span> <span class="kw">if</span> (!__traits(compiles, fun(Type.<span class="dt">init</span>)))
                <span class="kw">pragma</span>(msg, <span class="st">&quot;Bad testing combination: &quot;</span>
                          ~ fun.<span class="dt">stringof</span> ~ <span class="st">&quot; and &quot;</span> ~ Type.<span class="dt">stringof</span>);
    }
}

<span class="kw">unittest</span>
{
    test!(myFun).on!(QualifiedTypes);
}</code></pre>
<h4 id="filtering-type-tuples">Filtering Type Tuples</h4>
<p>You can search for and extract some types from a tuple, using a predicate to chose which type (or more generally, which tuple element) you want to keep. A predicate in this particular case means 'a template that, when given a type as argument, will return either <code class="sourceCode d"><span class="kw">true</span></code> or <code class="sourceCode d"><span class="kw">false</span></code>'. The test done on the tuple element can be as complicated as you want, particularly using <code class="sourceCode d"><span class="kw">is</span>()</code> expressions (see <a href="#the-is-expression">here</a>).</p>
<p>That gives us the following code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> staticfilter;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> staticFilter(<span class="kw">alias</span> Pred, T...)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// End of sequence</span>
        <span class="kw">alias</span> TypeTuple!() staticFilter;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Pred!(T[<span class="dv">0</span>]))
        <span class="kw">alias</span> TypeTuple!(T[<span class="dv">0</span>], staticFilter!(Pred, T[<span class="dv">1</span>..$])) staticFilter;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(      staticFilter!(Pred, T[<span class="dv">1</span>..$])) staticFilter;
}</code></pre>
<p>Using <code class="sourceCode d">staticFilter</code> is quite simple. Let's get integral types from a tuple, by way of <a href="http://dlang.org/phobos/std_traits.html#isIntegral">std.traits.isIntegral</a>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingstaticfilter1;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> staticfilter;

<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">float</span>, <span class="dt">string</span>, <span class="dt">byte</span>, <span class="dt">bool</span>, <span class="dt">float</span>, <span class="dt">void</span>) Types;

<span class="kw">alias</span> staticFilter!(isIntegral, Types) OnlyIntegrals;

<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(OnlyIntegrals == TypeTuple!(<span class="dt">int</span>, <span class="dt">byte</span>)));</code></pre>
<p>What about separating types from non-types? First, let's create a template that is <code class="sourceCode d"><span class="kw">true</span></code> for pure types and <code class="sourceCode d"><span class="kw">false</span></code> on non-types:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> istype;

<span class="kw">template</span> isType(T)
{
    <span class="kw">enum</span> isType = <span class="kw">true</span>;
}

<span class="kw">template</span> isType(<span class="kw">alias</span> a)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(a))
        <span class="kw">enum</span> isType = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> isType = <span class="kw">false</span>;
}</code></pre>
<p>Hey, wait! OK with having two specialised templates, one on template type parameters and another on aliases. But why the <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>? It's because user-defined types (<code class="sourceCode d">MyClass</code> and such) are <em>both</em> a type and a symbol (we saw that in section <a href="#template-declarations">Template Declarations</a>). For this particular use, I want them to be considered as types, contrary to other symbols (function names, module names, variables, ...). Hence the <code class="sourceCode d"><span class="kw">is</span></code><code class="sourceCode d">()</code> test. We can change things a bit to get a built-in types detector, which may also be interesting. Built-in types <em>cannot</em> be used as alias parameters, so let's test for that:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> isbuiltintype;

<span class="kw">template</span> isSymbol(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> isSymbol = <span class="kw">true</span>;
}

<span class="kw">template</span> isBuiltinType(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, isSymbol!(T)))
        <span class="kw">enum</span> isBuiltinType = <span class="kw">false</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> isBuiltinType = <span class="kw">true</span>;
}

<span class="kw">template</span> isBuiltinType(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> isBuiltinType = <span class="kw">false</span>;
}</code></pre>
<p>And, here we go:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingstaticfilter2;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> staticfilter;
<span class="kw">import</span> istype;
<span class="kw">import</span> isbuiltintype;

<span class="kw">class</span> MyClass {}
<span class="dt">int</span> foo(<span class="dt">int</span> i) { <span class="kw">return</span> i;}

<span class="kw">alias</span> staticFilter!(isType, <span class="dv">1</span>, <span class="dt">int</span>, <span class="fl">3.14</span>, <span class="st">&quot;abc&quot;</span>, foo, MyClass) Types;
<span class="kw">alias</span> staticFilter!(isBuiltinType, <span class="dv">1</span>, <span class="dt">int</span>, <span class="fl">3.14</span>, <span class="st">&quot;abc&quot;</span>, foo, MyClass) Builtins;

<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Types == TypeTuple!(<span class="dt">int</span>, MyClass)));
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Builtins == TypeTuple!(<span class="dt">int</span>)));</code></pre>
<p>But that is, admittedly, pretty run-of-the-mill stuff. Though useful from time to time, it's quite rare for someone to be given a pure type tuple like this. A much more common use for the likes of <code class="sourceCode d">staticFilter</code> is when creating complex types.</p>
<h3 id="example-building-a-graph">Example: building a <code>Graph</code></h3>
<p>As a first example, imagine you have a <code class="sourceCode d">Graph(Node, Edge)</code> struct, templated on the nodes (vertice) and edges types (themselves templated). When you create a <code class="sourceCode d">Graph</code> with a <a href="#factory-functions">factory function</a>, it would be nice to be able to mix nodes and edges in a natural way. That is, given <code class="sourceCode d">graph</code>, <code class="sourceCode d">node</code> and <code class="sourceCode d">edge</code> functions that do the obvious thing, you want to autorize calls like:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">/**</span>
<span class="co">* Automatically creates a graph</span>
<span class="co">*   - with four nodes labelled &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, holding a double,</span>
<span class="co">*   - with nodes linking &quot;A&quot; to &quot;B&quot;, &quot;D&quot; to &quot;A&quot; and &quot;D&quot; to &quot;C&quot;.</span>
<span class="co">*/</span>
<span class="kw">auto</span> g = graph(node(<span class="st">&quot;A&quot;</span>, <span class="fl">3.14159</span>), node(<span class="st">&quot;B&quot;</span>, <span class="fl">1.0</span>),
               edge(<span class="st">&quot;A&quot;</span>,<span class="st">&quot;B&quot;</span>),
               node(<span class="st">&quot;C&quot;</span>, <span class="fl">2.71828</span>), node(<span class="st">&quot;D&quot;</span>, <span class="fl">0.0</span>),
               edge(<span class="st">&quot;D&quot;</span>,<span class="st">&quot;A&quot;</span>), edge(<span class="st">&quot;D&quot;</span>, <span class="st">&quot;C&quot;</span>));</code></pre>
<p>This allows the user building her <code class="sourceCode d">Graph</code> to create nodes and edges between these nodes in a natural way (as opposed to, say, batch-building all nodes and then adding edges between them). But, as a library writer, that means your <code class="sourceCode d">graph</code> factory function has the following signature:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> graph(NodesOrEdges...)(NodesOrEdges args)
<span class="kw">if</span> (<span class="co">/* sanity check test on NodesOrEdges */</span>)</code></pre>
<p>Both the sanity check performed by the template constraint (<a href="#constraints">Constraints</a>) and the building code inside <code class="sourceCode d">graph</code> can be quite complicated. <code class="sourceCode d">staticFilter</code> helps by separating the arguments between nodes and edges. Without extending this example too much, say we have at our disposal the following predicate templates:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> isNode(N) {<span class="co">/* true iff N is a Node!(LabelType, ValueType)*/</span>}
<span class="kw">template</span> isEdge(E) {<span class="co">/* true iff E is an Edge!(LabelType)*/</span>}

<span class="kw">template</span> isNodeOrEdge(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (isNode!T || isEdge!T)
        <span class="kw">enum</span> isNodeOrEdge = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> isNodeOrEdge = <span class="kw">false</span>;
}</code></pre>
<p>And let's suppose also all <em>bona fide</em> <code class="sourceCode d">Node</code>s and <code class="sourceCode d">Edge</code>s have <code class="sourceCode d">.LabelType</code> and <code class="sourceCode d">.ValueType</code> members exposing their inner types (as shown in <a href="#inner-alias">Inner Alias</a>).</p>
<p>Then, getting all nodes and edges is easy:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">alias</span> staticFilter!(isNode, NodesOrEdges) Nodes;
<span class="kw">alias</span> staticFilter!(isEdge, NodesOrEdges) Edges;</code></pre>
<p>This is where things get interesting: obtaining the edges and nodes types is just a first building block. Now <code class="sourceCode d">graph</code> must check at a minimum the following elements:</p>
<ul>
<li>All arguments must be nodes or edges.</li>
<li>Is there at least <em>one</em> node in the list?</li>
<li>If yes, do all nodes have the same <code class="sourceCode d">LabelType</code> and the same <code class="sourceCode d">ValueType</code>, or, at least, is there a common type between all the labels' types and another one for the values stored in the nodes?</li>
<li>Do edges <code class="sourceCode d">LabelTypes</code> have a common type? (Note that there can be zero edges).</li>
<li>Do the edges labels have the correct type to refer to the provided nodes?</li>
</ul>
<p>Note that <em>all</em> these checks are done only on types and thus can be done at compile-time, thereby ensuring a pretty solid static check on the graph built. What cannot be done in this way is verifying during compilation that edges do indeed refer to existing nodes.</p>
<p>Let's use what we have seen until now to create the <code class="sourceCode d">GraphCheck</code> template, before seeing another <code class="sourceCode d">staticFilter</code> example:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">import</span> std.traits: CommonType;

<span class="kw">template</span> GraphCheck(NodesOrEdges...)
{
    <span class="kw">enum</span> GraphCheck = GraphCheckImpl!(NodesOrEdges).result;
}

<span class="kw">template</span> GraphCheckImpl(NodesOrEdges...)
{
    <span class="kw">alias</span> staticFilter!(isNode, NodesOrEdges) Nodes;
    <span class="kw">alias</span> staticFilter!(isEdge, NodesOrEdges) Edges;

    <span class="co">// 1. All arguments must be nodes or edges</span>
    <span class="kw">static</span> <span class="kw">assert</span> (Nodes.<span class="dt">length</span> + Edges.<span class="dt">length</span> != NodesOrEdges.<span class="dt">length</span>,
                   <span class="st">&quot;Some args are not nodes or edges.&quot;</span>);

    <span class="co">// 2. There must be at least one node</span>
    <span class="kw">static</span> <span class="kw">assert</span> (Nodes.<span class="dt">length</span> == <span class="dv">0</span>,
                   <span class="st">&quot;You must provide at least one node.&quot;</span>);

    <span class="co">// 3. Is there a common type for the nodes&#39; labels and values?</span>
    <span class="co">// First step: extracting labels and values</span>
    <span class="kw">template</span> GetLabel(T) <span class="kw">if</span> (isNode!T || isEdge!T)
    {
        <span class="kw">alias</span> T.LabelType GetLabel;
    }

    <span class="kw">template</span> GetValue(T) <span class="kw">if</span> (isNode!T)
    {
        <span class="kw">alias</span> T.ValueType GetValue;
    }

    <span class="kw">alias</span> staticMap!(GetLabel, Nodes) NodesLabels;
    <span class="kw">alias</span> staticMap!(GetValue, Nodes) NodesValues;

    <span class="kw">static</span> <span class="kw">assert</span> (<span class="kw">is</span>(CommonType!(NodesLabels) == <span class="dt">void</span>), <span class="co">// no common type</span>
                   <span class="st">&quot;The nodes do not have all the same label type.&quot;</span>);

    <span class="kw">static</span> <span class="kw">assert</span> (<span class="kw">is</span>(CommonType!(NodesValues) == <span class="dt">void</span>),
                   <span class="st">&quot;The nodes do not have all the same value type.&quot;</span>);

    <span class="co">// 4. Same for edges</span>
    <span class="kw">alias</span> staticMap!(GetLabel, Edges) EdgesLabels;

    <span class="kw">static</span> <span class="kw">assert</span> (<span class="kw">is</span>(CommonType!(EdgesLabels) == <span class="dt">void</span>),
                   <span class="st">&quot;The edges do not have all the same label type.&quot;</span>);

    <span class="co">// 5. Edges - Node compatibility</span>
    <span class="kw">static</span> <span class="kw">assert</span>(!<span class="kw">is</span>(CommonType!NodesLabels == CommonType!EdgesLabels),
                  <span class="st">&quot;Nodes and edges do not have the same label type.&quot;</span>);

    <span class="kw">enum</span> result = <span class="kw">true</span>;
}</code></pre>
<p>This is one huge template, but <code class="sourceCode d">staticFilter</code> sits square in the middle and greatly simplifies the code. Note the use of <code class="sourceCode d"><span class="kw">static</span> <span class="kw">assert</span></code>, slightly different from Now, <code class="sourceCode d">graph</code> signature is simply:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> graph(NodesOrEdges...)(NodesOrEdges args) <span class="kw">if</span> (GraphCheck!NodesOrEdges)
{ ... }</code></pre>
<blockquote>
<p><strong>Unfinished</strong> The second example will be one code generating a struct, with string literal and type parameters.</p>
</blockquote>
<h4 id="folding-type-tuples">Folding Type Tuples</h4>
<p>With mapping and filtering, folding (aka, reducing) is the third standard operation on sequences.<a href="#fn19" class="footnoteRef" id="fnref19"><sup>19</sup></a> The idea is the same as <a href="http://dlang.org/phobos/std_algorithm.html#reduce">std.algorithm.reduce</a>: given a seed <code>S</code> and a binary function <code class="sourceCode d">bin</code>, calculate <code class="sourceCode d">bin(bin(bin(S, T[<span class="dv">0</span>]),T[<span class="dv">1</span>],T[<span class="dv">2</span>],...))</code>: apply <code class="sourceCode d">bin</code> on the seed and the first type of the tuple, then take the resulting type as a new seed and re-apply <code class="sourceCode d">bin</code> to this and the second type of the tuple, and so on, until the entire tuple is used.</p>
<p>So, what's the use of such a function? It's used to <em>collapse</em> a type tuple into one type. This one type can a simple type (for example, the 'biggest' type in the tuple, for some definition of big) or a complex structure built iteratively step by step along the tuple: a binary tree holding all the types, for example, or the reverse of the tuple, or even all the types but sorted according to a predicate.</p>
<p>Here, we will see two examples: getting the maximum type and sorting a type tuple.</p>
<p>But first, here is <code class="sourceCode d">staticReduce</code>:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> staticreduce;

<span class="kw">template</span> staticReduce(<span class="kw">alias</span> bin, Types...) <span class="co">// Types[0] is the seed</span>
{
    <span class="kw">static</span> <span class="kw">if</span> (Types.<span class="dt">length</span> &lt; <span class="dv">2</span>)
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;staticReduce: tuple &quot;</span>
               ~ Types.<span class="dt">stringof</span> ~ <span class="st">&quot; has not enough elements (min: 2 elements)&quot;</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Types.<span class="dt">length</span> == <span class="dv">2</span>) <span class="co">// end of recursion</span>
        <span class="kw">alias</span> bin!(Types[<span class="dv">0</span>], Types[<span class="dv">1</span>]) staticReduce;
    <span class="kw">else</span> <span class="co">// recurse</span>
        <span class="kw">alias</span> staticReduce!(bin, bin!(Types[<span class="dv">0</span>], Types[<span class="dv">1</span>])
                               , Types[<span class="dv">2</span>..$])
              staticReduce;
}</code></pre>
<p>From here, how do we get the biggest type? Simple, just apply a <code class="sourceCode d">Max</code> binary template to your type list:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> maxtemplate;

<span class="kw">template</span> Max(T1, T2)
{
    <span class="kw">static</span> <span class="kw">if</span> (T1.<span class="dt">sizeof</span> &gt;= T2.<span class="dt">sizeof</span>)
        <span class="kw">alias</span> T1 Max;
    <span class="kw">else</span>
        <span class="kw">alias</span> T2 Max;
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingmax;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> maxtemplate;
<span class="kw">import</span> staticreduce;

<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">bool</span>, <span class="dt">double</span>, <span class="dt">float</span> <span class="kw">delegate</span>(<span class="dt">float</span>), <span class="dt">string</span>[]) Types;

<span class="kw">alias</span> staticReduce!(Max, Types) MaxType;
<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(MaxType == <span class="dt">float</span> <span class="kw">delegate</span>(<span class="dt">float</span>)));</code></pre>
<p>You can vary your definition of <code class="sourceCode d">Max</code> according to taste. Here I used the built-in <code class="sourceCode d">.<span class="dt">sizeof</span></code> property to compare two unknown types. To compare on the names, I'd have used <code class="sourceCode d">.<span class="dt">stringof</span></code> and so on.</p>
<h4 id="sorting-types">Sorting Types</h4>
<blockquote>
<strong>Ivory Tower Wankery!</strong> I mean, when would sorting types be useful? It can be useful, read on<br />
</blockquote>
<p>When can sorting a tuple be useful? Mainly for the same reason you'd want to sort any sequence:</p>
<ul>
<li>easily find a type (in <span class="math">log(<em>n</em>)</span>),</li>
<li>easily get afterwards the first <span class="math"><em>p</em></span> types or last <span class="math"><em>p</em></span> types,</li>
<li>compare two type tuples for equivalence,</li>
<li>easily getting rid of duplicates (transforming a tuple into a set of types).</li>
</ul>
<p>I'll focus on the third use, comparing two type tuples. See for example the <a href="http://dlang.org/phobos/std_variant.html#Algebraic">std.variant.Algebraic</a> template struct. <code class="sourceCode d">Algebraic!(Type0, Type1, ... TypeN)</code> can hold a value of one of <code class="sourceCode d">Type0</code>, <code class="sourceCode d">TypeN</code>. But of course, in a certain sense, the previous type is also the same as <code class="sourceCode d">Algebraic!(Type1, TypeN, ... Type0)</code> or any other reordering of the types. But that's not the case currently:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> variant_error;
<span class="kw">import</span> std.variant;

<span class="dt">void</span> main()
{
    Algebraic!(<span class="dt">int</span>, <span class="dt">double</span>, <span class="dt">string</span>) algOne;
    algOne = <span class="dv">1</span>;
    Algebraic!(<span class="dt">double</span>, <span class="dt">int</span>, <span class="dt">string</span>) algTwo = algOne; <span class="co">// fail!</span>
}</code></pre>
<p>Using sorted types internally (or even using a factory function to create algebraic values, that always returned sorted <code class="sourceCode d">Algebraic</code>) would allow for a seamless use of algebraic values.</p>
<p>Here is one way to sort types using <code class="sourceCode d">staticReduce</code>. The standard situation is the following: you have a list of already sorted types (the initial tuple's first <span class="math"><em>n</em></span> types) which is your current state, the value being constructed. <code class="sourceCode d">staticReduce</code> takes this list and puts the first remaining unsorted type in it and then reiterates on the next unsorted type. So the basic step is to add a new type to a sorted list.</p>
<p>A small problem arises: the state is just one type, but it has to store all the sorted types. It cannot be a naked type tuple, since these auto-flatten (see <a href="#definition-and-basic-properties">Tuple Properties</a>). We will use <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> to wrap it. Inner types of a <code class="sourceCode d">Tuple</code> are accessible through the <code class="sourceCode d">.Types</code> alias. I'm afraid that will uglify the code a bit.</p>
<p>Finally, what predicate to use? <code class="sourceCode d">.<span class="dt">sizeof</span></code> is not adequate: many different types have the same size and that would have a bad consequence, as the initial order would influence the sorted order. I'll just use the stringified version of the types, obtained by the built-in <code class="sourceCode d">.<span class="dt">stringof</span></code> property:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> sorttypes;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> staticreduce;

<span class="kw">template</span> Max(T1, T2)
{
    <span class="kw">static</span> <span class="kw">if</span> (T1.<span class="dt">stringof</span> &gt;= T2.<span class="dt">stringof</span>)
        <span class="kw">alias</span> T1 Max;
    <span class="kw">else</span>
        <span class="kw">alias</span> T2 Max;
}

<span class="kw">template</span> AddToSorted(Sorted, Type)
{
<span class="co">// Length 0: already sorted</span>
    <span class="kw">static</span> <span class="kw">if</span> (Sorted.Types.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">alias</span> Tuple!(Type) AddToSorted;
<span class="co">// Smaller than the first one: put Type in first place</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Max!(Sorted.Types[<span class="dv">0</span>], Type) == Sorted.Types[<span class="dv">0</span>]))
        <span class="kw">alias</span> Tuple!(Type, Sorted.Types) AddToSorted;
<span class="co">// Bigger than the last one: put Type at the end</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Max!(Sorted.Types[$-<span class="dv">1</span>], Type) == Type))
        <span class="kw">alias</span> Tuple!(Sorted.Types, Type) AddToSorted;
<span class="co">// Else, compare to the middle type and recurse left or right of it</span>
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(Max!(Sorted.Types[$/<span class="dv">2</span>], Type) == Type))
        <span class="kw">alias</span> Tuple!(Sorted.Types[<span class="dv">0</span>..$/<span class="dv">2</span>],
                     AddToSorted!(Tuple!(Sorted.Types[$/<span class="dv">2</span>..$]),Type).Types)
              AddToSorted;
    <span class="kw">else</span>
        <span class="kw">alias</span> Tuple!(AddToSorted!(Tuple!(Sorted.Types[<span class="dv">0</span>..$/<span class="dv">2</span>]),Type).Types,
                     Sorted.Types[$/<span class="dv">2</span>..$])
              AddToSorted;
}

<span class="kw">template</span> Sort(Types...)
{
    <span class="kw">alias</span> staticReduce!(AddToSorted, Tuple!(), Types) Sort;
}</code></pre>
<p>As I said, in the end <code class="sourceCode d">Sort</code> is just applying <code class="sourceCode d">AddToSorted</code> to the target tuple. The initial (seed) state for <code class="sourceCode d">staticReduce</code> is an empty typetuple, <code class="sourceCode d">Tuple!()</code>.</p>
<p>Now, does that work? You bet:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> sortingtypes;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> sorttypes;

<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">bool</span>, <span class="dt">string</span> <span class="kw">function</span>(<span class="dt">int</span>), <span class="dt">float</span>[]) Types1;
<span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">float</span>[], <span class="dt">string</span> <span class="kw">function</span>(<span class="dt">int</span>), <span class="dt">bool</span>) Types2;

<span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Sort!Types1 == Sort!Types2));</code></pre>
<p>If you do not like sorting types alphabetically by name, you can resort to other definitions of <code class="sourceCode d">Max</code> or, even better, make a version of <code class="sourceCode d">Sort</code> that accepts another, binary, template as an argument and uses this template as way to determine ordering.</p>
<blockquote>
<p><strong>What about non-types?</strong> As was said at the very beginning of the section, the templates presented here work most of the time for other template parameters: pure numbers, strings, aliases, Here you'd have to change <code class="sourceCode d">AddToSorted</code> second parameter to accept non-types. Or, another way to do it would be to first map a stringifier on the tuple's elements and <em>then</em> sort the resulting strings.</p>
</blockquote>
<h3 id="scanning-types-interleaving-types-crossing-types">Scanning Types, Interleaving Types, Crossing Types</h3>
<blockquote>
<p><strong>TODO</strong> Determine if this subsection is really useful. Is there any short and telling example?</p>
</blockquote>
<h4 id="static-scan">Static Scan</h4>
<p>A <em>scan</em> is a sort of <code class="sourceCode d">reduce</code>/<code class="sourceCode d">fold</code> operation (see <a href="#folding-type-tuples">Folding Type Tuples</a>), but giving the intermediary results. It's used by the <code class="sourceCode d">juxtapose</code> template in <a href="#juxtaposing-functions">Juxtaposing Functions</a>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> staticscan;
<span class="kw">import</span> std.typetuple;

<span class="co">/**</span>
<span class="co">Gives the TypeTuple resulting from the successive applications of F to reduce</span>
<span class="co">the T list.</span>
<span class="co">*/</span>
<span class="kw">template</span> StaticScan(<span class="kw">alias</span> F, T...)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">alias</span> TypeTuple!() StaticScan; <span class="co">// This case should never happen with normal use</span>
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">1</span>)
        <span class="kw">alias</span> TypeTuple!(T[<span class="dv">0</span>]) StaticScan;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(T[<span class="dv">0</span>], StaticScan!(F, F!(T[<span class="dv">0</span>], T[<span class="dv">1</span>]), T[<span class="dv">2</span>..$])) StaticScan;
}</code></pre>
<h4 id="interleaving-types">Interleaving Types</h4>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> interleave;
<span class="kw">import</span> std.typetuple;

<span class="co">/**</span>
<span class="co"> * Given (T0, T1, T2, ..., Tn) and (U0, U1, ..., Um) will returns</span>
<span class="co"> * the interleaving of the first part with the second part:</span>
<span class="co"> *</span>
<span class="co"> * (T0, U0, T1, U1, ...</span>
<span class="co"> *</span>
<span class="co"> * If one of the inputs is shorter than the other,</span>
<span class="co"> * the longer part is put at the end of the interleaving.</span>
<span class="co"> */</span>
<span class="kw">template</span> Interleave(First...)
{
    <span class="kw">template</span> With(Second...)
    {
        <span class="kw">static</span> <span class="kw">if</span> (First.<span class="dt">length</span> == <span class="dv">0</span>)
            <span class="kw">alias</span> Second With;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Second.<span class="dt">length</span> == <span class="dv">0</span>)
            <span class="kw">alias</span> First With;
        <span class="kw">else</span>
            <span class="kw">alias</span> TypeTuple!( First[<span class="dv">0</span>], Second[<span class="dv">0</span>]
                            , Interleave!(First[<span class="dv">1</span>..$]).With!(Second[<span class="dv">1</span>..$]))
                 With;
    }
}</code></pre>
<h3 id="annotating-types">Annotating Types</h3>
<blockquote>
<p><strong>Unfinished</strong> The idea is to wrap values in a template adding some meta data. Ideally, I'd like to get things like the following code to work:</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> arr = [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>]; <span class="co">// Array of ints</span>
<span class="kw">auto</span> arr2 = sorted(arr); <span class="co">// Now, we know it&#39;s sorted</span>
<span class="kw">auto</span> arr3 = positive(arr2); <span class="co">// Sorted *and* all elements are positive</span></code></pre>
<p>Or, more generally:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> arr = [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>]; <span class="co">// Array of ints</span>
<span class="kw">auto</span> arr2 = annotate!(<span class="st">&quot;sorted&quot;</span>, (a,b) =&gt; a&lt;b)(arr);
<span class="kw">auto</span> arr3 = annotate!(<span class="st">&quot;positive&quot;</span>)(arr2);

<span class="kw">assert</span>(<span class="st">&quot;positive&quot;</span> <span class="kw">in</span> arr3.properties);
<span class="kw">assert</span>(arr3.Properties == TypeTuple!( Property!(<span class="st">&quot;sorted&quot;</span>, (a,b) =&gt; a &lt; b)
                                    , Property!(<span class="st">&quot;positive&quot;</span>)));

<span class="co">// the wrapped value is still there:</span>
<span class="kw">auto</span> arr4 = array(filter!((a) =&gt; a%<span class="dv">2</span>==<span class="dv">0</span>))(arr3);
<span class="co">// getting rid of some properties</span>
<span class="kw">auto</span> arr5 = arr3.discardProperty!<span class="st">&quot;positive&quot;</span>;
<span class="kw">assert</span>(arr5.Properties == TypeTuple!(Property!(<span class="st">&quot;sorted&quot;</span>, (a,b) =&gt; a &lt; b)));

<span class="kw">auto</span> arr6 = annotate!(<span class="st">&quot;negative&quot;</span>)([-<span class="dv">4</span>, -<span class="dv">3</span>, -<span class="dv">2</span>, -<span class="dv">1</span>]);
<span class="kw">auto</span> arr7 = annotate!(<span class="st">&quot;sorted&quot;</span>, (a,b) =&gt; a&lt;b)(arr6);

<span class="kw">assert</span>(arr3.property!<span class="st">&quot;sorted&quot;</span> == arr7.property!<span class="st">&quot;sorted&quot;</span>); <span class="co">// same predicate</span></code></pre>
<p>Here is a first <em>very rough and unfinished</em> draft:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> annotation;
<span class="kw">import</span> std.typetuple;

<span class="kw">struct</span> Meta(<span class="dt">string</span> Name, <span class="kw">alias</span> Data)
{
    <span class="kw">enum</span> name = Name;
    <span class="kw">alias</span> Data data;
}

<span class="kw">template</span> isMeta(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (__traits(hasMember, T, <span class="st">&quot;name&quot;</span>)
            &amp;&amp; __traits(hasMember, T, <span class="st">&quot;data&quot;</span>))
        <span class="kw">enum</span> isMeta = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> isMeta = <span class="kw">false</span>;
}

<span class="kw">template</span> GetName(<span class="kw">alias</span> a)
{
    <span class="kw">enum</span> <span class="dt">string</span> GetName = a.name;
}

<span class="kw">template</span> isAnnotated(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, T.Annotations))
        <span class="kw">enum</span> <span class="dt">bool</span> isAnnotated = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">bool</span> isAnnotated = <span class="kw">false</span>;
}

<span class="dt">string</span> getNames(Metadata...)() @property
{
    <span class="kw">alias</span> staticMap!(GetName, Metadata) names;
    <span class="dt">string</span> result;
    <span class="kw">foreach</span>(name; names)
        result ~= <span class="st">&quot;\&quot;&quot;</span>~name~<span class="st">&quot;\&quot;,&quot;</span>;
    <span class="kw">if</span> (names.<span class="dt">length</span>) result = result[<span class="dv">0</span>..$-<span class="dv">1</span>];
    <span class="kw">return</span> <span class="st">&quot;alias TypeTuple!(&quot;</span> ~ result ~ <span class="st">&quot;) names;&quot;</span>;
}

<span class="kw">struct</span> Annotated(T, Metadata...)
<span class="kw">if</span> (allSatisfy!(isMeta, Metadata))
{
    T value;
    <span class="kw">alias</span> value <span class="kw">this</span>;
    <span class="kw">mixin</span>(getNames!(Metadata));
    Metadata metadata;

    <span class="kw">auto</span> property(<span class="dt">string</span> s)() @property
    {
        <span class="kw">static</span> <span class="kw">if</span> (staticIndexOf!(s, names) != -<span class="dv">1</span>)
            <span class="kw">return</span> metadata[staticIndexOf!(s, names)];
        <span class="kw">else</span>
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">false</span>, <span class="st">&quot;Unknown property: &quot;</span> ~ s);
    }

    <span class="dt">bool</span> hasAnnotation(<span class="dt">string</span> name) @property
    {
        <span class="kw">foreach</span>(n; names)
            <span class="kw">if</span> (name == n) <span class="kw">return</span> <span class="kw">true</span>;
        <span class="kw">return</span> <span class="kw">false</span>;
    }
}

<span class="co">// auto annotated(T)(T value)</span>
<span class="co">// {</span>
<span class="co">//     return Annotated!(T)(value);</span>
<span class="co">// }</span>

<span class="kw">template</span> annotated(Metadata...) <span class="kw">if</span> (Metadata.<span class="dt">length</span>)
{
    <span class="kw">auto</span> annotated(T)(T value)
    {
    <span class="co">//     alias TypeTuple!(Metadata) MetaTypes;</span>
        <span class="kw">static</span> <span class="kw">if</span> (isAnnotated!(T))
            <span class="kw">return</span> Annotated!(T.AnnotatedType, T.Annotations, Metadata)(value.value);
        <span class="kw">else</span>
        {
            Annotated!(T, Metadata) a;
            a.value = value;
            <span class="kw">return</span> a;
        }
    }
}</code></pre>
<h2 id="tuples-as-sequences">Tuples as Sequences</h2>
<blockquote>
<p><strong>Unfinished</strong> The idea here is to treat tuples of values (is in <code class="sourceCode d">tuple(<span class="dv">1</span>, <span class="st">&quot;abc&quot;</span>, <span class="fl">3.14</span>, <span class="dv">3</span>, <span class="dv">0</span>)</code> as sequences: map a (polymorphic, aka templated) function on them, filter them, etc. Why do that: imagine for example having a bunch of ranges, all of a different type. If you want to group them in a range and process them, you can't because a range must be homogeneous in type. The functions presented there lift that restriction.</p>
</blockquote>
<h3 id="mapping-on-tuples">Mapping on Tuples</h3>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> maptuple;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.functional;

<span class="co">/**</span>
<span class="co"> * Helper template to get a template function return type.</span>
<span class="co"> */</span>
<span class="kw">template</span> RT(<span class="kw">alias</span> fun)
{
    <span class="kw">template</span> RT(T)
    {
        <span class="kw">alias</span> <span class="dt">typeof</span>(fun(T.<span class="dt">init</span>)) RT;
    }
}

<span class="co">/// Maps on a tuple, using a polymorphic function. Produces another tuple.</span>
Tuple!(staticMap!(RT!fun, T)) mapTuple(<span class="kw">alias</span> fun, T...)(Tuple!T tup)
{
    StaticMap!(RT!fun, T) res;
    <span class="kw">foreach</span>(i, Type; T) res[i] = unaryFun!fun(tup.field[i]);
    <span class="kw">return</span> tuple(res);
}</code></pre>
<h3 id="filtering-tuples">Filtering Tuples</h3>
<blockquote>
<p><strong>Unfinished</strong> The idea here is to filter a tuple with a predicate acting on types. It's quite useful when you can get a bunch of parameters in a function and want only some of them. See <a href="#filtering-type-tuples">Filtering Type Tuples</a> to see an example with the <code class="sourceCode d">graph</code> function.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> filtertuple;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> FilterTupleTypes(<span class="kw">alias</span> pred, <span class="kw">alias</span> tup)
{
    <span class="kw">static</span> <span class="kw">if</span> (tup.field.<span class="dt">length</span>)
    {
        <span class="kw">static</span> <span class="kw">if</span> (pred(tup.field[<span class="dv">0</span>]))
            <span class="kw">alias</span> TypeTuple!(tup.Types[<span class="dv">0</span>], FilterTupleTypes!(pred, tuple(tup.expand[<span class="dv">1</span>..$])))
                  FilterTupleTypes;
        <span class="kw">else</span>
            <span class="kw">alias</span> FilterTupleTypes!(pred, tuple(tup.expand[<span class="dv">1</span>..$]))
                  FilterTupleTypes;
    }
    <span class="kw">else</span>
    {
        <span class="kw">alias</span> TypeTuple!() FilterTupleTypes;
    }

}

<span class="kw">template</span> FilterTupleIndices(<span class="kw">alias</span> pred, <span class="kw">alias</span> tup, <span class="dt">size_t</span> ind)
{
    <span class="kw">static</span> <span class="kw">if</span> (tup.field.<span class="dt">length</span>)
    {
        <span class="kw">static</span> <span class="kw">if</span> (pred(tup.field[<span class="dv">0</span>]))
            <span class="kw">alias</span> TypeTuple!( ind
                            , FilterTupleIndices!( pred
                                                 , tuple(tup.expand[<span class="dv">1</span>..$])
                                                 , ind+<span class="dv">1</span>
                                                 )
                            ) FilterTupleIndices;
        <span class="kw">else</span>
            <span class="kw">alias</span> FilterTupleIndices!( pred
                                     , tuple(tup.expand[<span class="dv">1</span>..$])
                                     , ind+<span class="dv">1</span>
                                     ) FilterTupleIndices;
    }
    <span class="kw">else</span>
    {
        <span class="kw">alias</span> TypeTuple!() FilterTupleIndices;
    }

}

<span class="co">/// Filter a tuple on its values.</span>
Tuple!(FilterTupleTypes!(pred, tup)) filterTuple(<span class="kw">alias</span> pred, <span class="kw">alias</span> tup)()
{
    FilterTupleTypes!(pred, tup) result;
    <span class="kw">alias</span> FilterTupleIndices!(pred, tup, <span class="dv">0</span>) indices;
    <span class="kw">foreach</span>(i, ind; indices)
    {
        result[i] = tup.field[ind];
    }
    <span class="kw">return</span> tuple(result);
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d">(<span class="dv">1</span>, <span class="st">&quot;abc&quot;</span>, <span class="dv">2</span>, <span class="st">&quot;def&quot;</span>, <span class="fl">3.14</span>)
-&gt;
((<span class="dv">1</span>,<span class="dv">2</span>),(<span class="st">&quot;abc&quot;</span>,<span class="st">&quot;def&quot;</span>),(<span class="dv">3</span>,<span class="dv">14</span>))</code></pre>
<h2 id="fun-with-functions">Fun With Functions</h2>
<p>This section will present some templates acting on functions or templated wrappers around functions, to expand them. It's not part of <a href="#function-templates">Function-Templates</a> because it uses struct templates and it's not part of <a href="#struct-templates">Struct Templates</a> because the wrapper struct is not the main focus of attention.</p>
<h3 id="determining-a-functions-number-of-arguments">Determining a Function's Number of Arguments</h3>
<blockquote>
<p><strong>Unfinished</strong> This is old code, see if anything changed about that in the past two years.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> functionarity;
<span class="kw">import</span> std.traits;

<span class="kw">template</span> arity(<span class="kw">alias</span> fun)
<span class="kw">if</span> (isFunction!fun)
{
    <span class="kw">enum</span> <span class="dt">size_t</span> arity = ParameterTypeTuple!(fun).<span class="dt">length</span>;
}</code></pre>
<h3 id="memoizing-a-function">Memoizing a Function</h3>
<p>When a function does long calculations, it might be efficient to store the computed results in an external structure and to query this structure for the result instead of calling the function again. This is called <em>memoizing</em> (not <em>memorizing</em>) and this section will show how to use a template to have some memoizing fun.</p>
<p>The previously-seen results are stored in an associative array, indexed on tuples of arguments. To get a function return type or parameter type tuple, just use Phobos' <a href="http://dlang.org/phobos/std_traits.html#ReturnType">std.traits.ReturnType</a> and <a href="http://dlang.org/phobos/std_traits.html#ParameterTypeTuple">std.traits.ParameterTypeTuple</a>, which are templates that accept function <em>names</em> or types.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> memoize1;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.typecons;

<span class="kw">struct</span> Memoize(<span class="kw">alias</span> fun)
{
    <span class="kw">alias</span> ReturnType!fun RT;
    <span class="kw">alias</span> ParameterTypeTuple!fun PTT;
    RT[Tuple!(PTT)] memo; <span class="co">// stores the result, indexed by arguments.</span>

    RT opCall(PTT args)
    {
        <span class="kw">if</span> (tuple(args) <span class="kw">in</span> memo)      <span class="co">// Have we already seen these args?</span>
        {
            <span class="kw">return</span> memo[tuple(args)]; <span class="co">// if yes, use the stored result</span>
        }
        <span class="kw">else</span> <span class="co">// if not, compute the result and store it.</span>
        {
            RT result = fun(args);
            memo[tuple(args)] = result;
            <span class="kw">return</span> result;
        }
    }
}

Memoize!fun memoize(<span class="kw">alias</span> fun)()
{
    Memoize!fun memo;
    <span class="kw">return</span> memo;
}</code></pre>
<p>Usage is very simple:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingmemoize1;
<span class="kw">import</span> memoize1;

<span class="dt">int</span> veryLongCalc(<span class="dt">int</span> i, <span class="dt">double</span> d, <span class="dt">string</span> s)
{
    <span class="co">/* ... cheating here ... */</span>
    <span class="kw">return</span> i;
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> vlcMemo = memoize!(veryLongCalc);

   <span class="co">// calculate veryLongCalc(1, 3.14, &quot;abc&quot;)</span>
   <span class="co">// takes minutes!</span>
   <span class="dt">int</span> res1 = vlcMemo(<span class="dv">1</span>, <span class="fl">3.14</span>, <span class="st">&quot;abc&quot;</span>);
   <span class="dt">int</span> res2 = vlcMemo(<span class="dv">2</span>, <span class="fl">2.718</span>, <span class="st">&quot;def&quot;</span>);<span class="co">// minutes again!</span>
   <span class="dt">int</span> res3 = vlcMemo(<span class="dv">1</span>, <span class="fl">3.14</span>, <span class="st">&quot;abc&quot;</span>); <span class="co">// a few ms to get res3</span>
}</code></pre>
<p>The above code is trivial and could be optimized in many ways. Mostly, a real memoizing template should also modify its behavior with storing policies. For example:</p>
<ul>
<li>No-limit or limited size store?</li>
<li><p>In case of limited-size store: how to define the limit and what should be the eviction policy?</p></li>
<li>First-in/First-out memo?</li>
<li>Least recenly used memo?</li>
<li>Least used?</li>
<li>Time-to-live?</li>
<li>Discard all and flush the store?</li>
<li>Discard only a fraction?</li>
<li><p>Stop memoizing?</p></li>
</ul>
<p>The last X results could be stored in a queue: each time a result is pushed into the associative array, push the arguments tuples in the queue. Once you reach the maximum store limit, discard the oldest one or (for example) half the stored values.</p>
<p>Here is a possible small implementation. It makes for a nice example of enabling/disabling code with <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> and <code class="sourceCode d"><span class="kw">enum</span></code>-based policies. Note that I use D dynamic arrays as a primitive queue. A real queue could probably be more efficient, but there isn't one in the standard library as of this writing.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> memoize2;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.typecons;

<span class="kw">enum</span> Storing {
    always,  <span class="co">// there is no tomorrow</span>
    maximum  <span class="co">// sustainable growth</span>
}

<span class="kw">enum</span> Discarding {
    oldest,   <span class="co">// only discard the oldest result</span>
    fraction, <span class="co">// discard a fraction (0.5 == 50%)</span>
    all       <span class="co">// burn, burn!</span>
}

<span class="kw">struct</span> Memoize(<span class="kw">alias</span> fun,
               Storing storing,
               Discarding discarding)
{
    <span class="kw">alias</span> ReturnType!fun RT;
    <span class="kw">alias</span> ParameterTypeTuple!fun PTT;

    <span class="kw">static</span> <span class="kw">if</span> (storing == Storing.maximum)
    {
        Tuple!(PTT)[] argsQueue;
        <span class="dt">size_t</span> maxNumStored;
    }

    <span class="kw">static</span> <span class="kw">if</span> (discarding == Discarding.fraction)
        <span class="dt">float</span> fraction;

    RT[Tuple!(PTT)] memo; <span class="co">// stores the result, indexed by arguments.</span>

    RT opCall(PTT args)
    {
        <span class="kw">if</span> (tuple(args) <span class="kw">in</span> memo)      <span class="co">// Have we already seen these args?</span>
        {
            <span class="kw">return</span> memo[tuple(args)]; <span class="co">// if yes, use the stored result</span>
        }
        <span class="kw">else</span>                          <span class="co">// if not,</span>
        {
            <span class="kw">static</span> <span class="kw">if</span> (storing == Storing.always)
            {
                RT result = fun(args);<span class="co">// compute the result and store it.</span>
                memo[tuple(args)] = result;
                <span class="kw">return</span> result;
            }
            <span class="kw">else</span> <span class="co">// Storing.maximum</span>
            {
                <span class="kw">if</span> (argsQueue.<span class="dt">length</span> &gt;= maxNumStored)
                {
                    <span class="kw">static</span> <span class="kw">if</span> (discarding == Discarding.oldest)
                    {
                        memo.remove(argsQueue[<span class="dv">0</span>]);
                        argsQueue = argsQueue[<span class="dv">1</span>..$];
                    }
                    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (discarding == Discarding.fraction)
                    {
                        <span class="kw">auto</span> num = to!<span class="dt">size_t</span>(argsQueue.<span class="dt">length</span> * fraction);
                        <span class="kw">foreach</span>(elem; argsQueue[<span class="dv">0</span>..num])
                            memo.remove(elem);
                        argsQueue = argsQueue[num..$];
                    }
                    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (discarding == Discarding.all)
                    {
                        memo = <span class="kw">null</span>;
                        argsQueue.<span class="dt">length</span> = <span class="dv">0</span>;
                    }
                }

                RT result = fun(args);<span class="co">// compute the result and store it.</span>
                memo[tuple(args)] = result;
                argsQueue ~= tuple(args);
                <span class="kw">return</span> result;
            }
        }
    }
}</code></pre>
<p>And a few factory function to help creating those <code class="sourceCode d">Memoize</code> structs:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> memoize3;
<span class="kw">import</span> memoize2;

<span class="co">// No runtime arg -&gt; always store</span>
Memoize!(fun, Storing.always, Discarding.all)
memoize(<span class="kw">alias</span> fun)()
{
    Memoize!(fun,
             Storing.always,
             Discarding.all) result;
    <span class="kw">return</span> result;
}

<span class="co">// One runtime size_t arg -&gt; maximum store / discarding all</span>
Memoize!(fun, Storing.maximum, Discarding.all)
memoize(<span class="kw">alias</span> fun)(<span class="dt">size_t</span> max)
{
    Memoize!(fun,
             Storing.maximum,
             Discarding.all) result;
    result.maxNumStored = max;
    <span class="kw">return</span> result;
}

<span class="co">// Two runtime args (size_t, double) -&gt; maximum store / discarding a fraction</span>
Memoize!(fun, Storing.maximum, Discarding.fraction)
memoize(<span class="kw">alias</span> fun)(<span class="dt">size_t</span> max, <span class="dt">double</span> fraction)
{
    Memoize!(fun,
             Storing.maximum,
             Discarding.fraction) result;
    result.maxNumStored = max;
    result.fraction = fraction;
    <span class="kw">return</span> result;
}

<span class="co">// One compile-time argument (discarding oldest), one runtime argument (max)</span>
Memoize!(fun, Storing.maximum, discarding)
memoize(<span class="kw">alias</span> fun, Discarding discarding = Discarding.oldest)
(<span class="dt">size_t</span> max)
{
    Memoize!(fun,
             Storing.maximum,
             Discarding.oldest) result;
    result.maxNumStored = max;
    <span class="kw">return</span> result;
}</code></pre>
<p>Note that, due to the introduction of an <code class="sourceCode d">opCall</code> operator, it's not possible to use a struct literal. We have to first create the struct, then initialize its fields.</p>
<p>Most of the time, the type of runtime arguments is enough to determine what you want as a memoizing/storing behavior. Only for the (rarer?) policy of discarding only the oldest stored result does the user need to indicate it with a template argument:</p>
<pre class="sourceCode d"><code class="sourceCode d">moduleusingmemoize3;
<span class="kw">import</span> memoize3;

<span class="dt">int</span> veryLongCalc(<span class="dt">int</span> i, <span class="dt">double</span> d, <span class="dt">string</span> s)
{
   <span class="co">/* ... cheating here ... */</span>
   <span class="kw">return</span> i,;
}

<span class="dt">void</span> main()
{
    <span class="co">// Store the first million results, flush the memo on max</span>
    <span class="kw">auto</span> vlcMemo1 = memoize!(veryLongCalc)(<span class="dv">1_000_000</span>);

    <span class="co">// Store the first million results, flush half the memo on max</span>
    <span class="kw">auto</span> vlcMemo2 = memoize!(veryLongCalc)(<span class="dv">1_000_000</span>, <span class="fl">0.5f</span>);

    <span class="co">// Store first twenty results, discard only the oldest</span>
    <span class="kw">auto</span> vlcMemo3 = memoize!(veryLongCalc, Discarding.oldest)(<span class="dv">20</span>);
}</code></pre>
<h3 id="currying-a-function">Currying a Function</h3>
<blockquote>
<p><strong>Unfinished</strong> Some explanations would greatly help there.</p>
</blockquote>
<p>Another useful transform on functions is to <em>curry</em> them:<a href="#fn20" class="footnoteRef" id="fnref20"><sup>20</sup></a> to transform a <span class="math"><em>n</em></span>-args function into <span class="math"><em>n</em></span> one-parameter functions inside another.</p>
<blockquote>
<p><strong>TODO</strong> Show some example: mapping a range for example.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> checkcompatibility;

<span class="kw">template</span> CheckCompatibility(T...)
{
    <span class="kw">template</span> With(U...)
    {
        <span class="kw">static</span> <span class="kw">if</span> (U.<span class="dt">length</span> != T.<span class="dt">length</span>)
            <span class="kw">enum</span> With = <span class="kw">false</span>;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span>  (T.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// U.length == 0 also</span>
            <span class="kw">enum</span> With = <span class="kw">true</span>;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (!<span class="kw">is</span>(U[<span class="dv">0</span>] : T[<span class="dv">0</span>]))
            <span class="kw">enum</span> With = <span class="kw">false</span>;
        <span class="kw">else</span>
            <span class="kw">enum</span> With = CheckCompatibility!(T[<span class="dv">1</span>..$]).With!(U[<span class="dv">1</span>..$]);
    }
}</code></pre>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> curry;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> checkcompatibility;

<span class="kw">struct</span> Curry(<span class="kw">alias</span> fun, <span class="dt">int</span> index = <span class="dv">0</span>)
{
    <span class="kw">alias</span> ReturnType!fun RT;
    <span class="kw">alias</span> ParameterTypeTuple!fun PTT;
    PTT args;

    <span class="kw">auto</span> opCall(V...)(V values)
        <span class="kw">if</span> (V.<span class="dt">length</span> &gt; <span class="dv">0</span>
         &amp;&amp; V.<span class="dt">length</span> + index &lt;= PTT.<span class="dt">length</span>)
    {
        <span class="co">// Is fun directly callable with the provided arguments?</span>
        <span class="kw">static</span> <span class="kw">if</span> (__traits(compiles, fun(args[<span class="dv">0</span>..index], values)))
            <span class="kw">return</span> fun(args[<span class="dv">0</span>..index], values);
        <span class="co">// If not, the new args will be stored. We check their types.</span>
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (!CheckCompatibility!(PTT[index..index + V.<span class="dt">length</span>]).With!(V))
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;curry: bad arguments. Waited for &quot;</span>
                            ~ PTT[index..index + V.<span class="dt">length</span>].<span class="dt">stringof</span>
                            ~ <span class="st">&quot; but got &quot;</span> ~ V.<span class="dt">stringof</span>);
        <span class="co">// not enough args yet. We store them.</span>
        <span class="kw">else</span>
        {
            Curry!(fun, index+V.<span class="dt">length</span>) c;
            <span class="kw">foreach</span>(i,a; args[<span class="dv">0</span>..index]) c.args[i] = a;
            <span class="kw">foreach</span>(i,v; values) c.args[index+i] = v;
            <span class="kw">return</span> c;
        }
    }
}

<span class="kw">auto</span> curry(<span class="kw">alias</span> fun)()
{
    Curry!(fun,<span class="dv">0</span>) c;
    <span class="kw">return</span> c;
}</code></pre>
<h3 id="juxtaposing-functions">Juxtaposing Functions</h3>
<blockquote>
<p><strong>Unfinished</strong> The idea is to glue functions together, to map on many ranges in parallel and create another multiple-value range afterwards.</p>
</blockquote>
<p>The functions are juxtaposed, that is, given:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="dt">int</span> foo(<span class="dt">int</span> i, <span class="dt">int</span> j) { <span class="kw">return</span> i+j;}
<span class="dt">string</span> bar() { <span class="kw">return</span> <span class="st">&quot;Hello, World&quot;</span>;}
<span class="dt">double</span> baz(<span class="dt">double</span> d) { <span class="kw">return</span> d*d;}</code></pre>
<p>Then <code class="sourceCode d">juxtapose!(foo,bar,baz)</code> is a function accepting two <code class="sourceCode d"><span class="dt">int</span></code>s and a <code class="sourceCode d"><span class="dt">double</span></code> as arguments and returning a tuple holding an <code class="sourceCode d"><span class="dt">int</span></code>, a <code class="sourceCode d"><span class="dt">string</span></code> and a <code class="sourceCode d"><span class="dt">double</span></code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> juxtapose;
<span class="kw">import</span> juxtaposehelper;

<span class="kw">template</span> juxtapose(Funs...)
{
    Tuple!(staticFilter!(isNotVoid, ReturnTypes!Funs))
    juxtapose(ParameterTypeTuples!Funs params)
    {
        <span class="dt">typeof</span>(<span class="kw">return</span>) result;
        <span class="kw">alias</span> SumOfArities!Funs arities;
        <span class="kw">alias</span> SumOfReturns!Funs returns;
        <span class="kw">foreach</span>(i, Fun; Funs)
        {
            <span class="kw">enum</span> firstParam = arities[i];
            <span class="kw">enum</span> lastParam = firstParam + arity!(Fun);
            <span class="kw">static</span> <span class="kw">if</span> (returns[i] != returns[i+<span class="dv">1</span>])
                result.field[returns[i]] = Fun(params[firstParam..lastParam]);
        }
        <span class="kw">return</span> result;
    }
}</code></pre>
<p>Necessary scaffolding:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> juxtaposehelper;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> functionarity;
<span class="kw">import</span> staticscan;
<span class="kw">import</span> maponalias;

<span class="kw">template</span> isNotVoid(T)
{
    <span class="kw">enum</span> <span class="dt">bool</span> isNotVoid = !<span class="kw">is</span>(T == <span class="dt">void</span>);
}

<span class="co">/**</span>
<span class="co"> * Given a bunch of functions names, gives the typetuple of their return types.</span>
<span class="co"> * Used by juxtapose.</span>
<span class="co"> */</span>
<span class="kw">template</span> ReturnTypes(Funs...)
{
    <span class="kw">alias</span> MapOnAlias!(ReturnType, Funs) ReturnTypes;
}

<span class="co">/**</span>
<span class="co"> * Given a bunch of functions names, gives the (flattened) typetuple</span>
<span class="co"> * of their return values. Used by juxtapose.</span>
<span class="co"> */</span>
<span class="kw">template</span> ParameterTypeTuples(<span class="kw">alias</span> fun, Rest...)
{
    <span class="kw">alias</span> MapOnAlias!(ParameterTypeTuple, fun, Rest) ParameterTypeTuples;
}

<span class="kw">template</span> SumOfArity(<span class="dt">size_t</span> zero, <span class="kw">alias</span> fun)
{
    <span class="kw">enum</span> <span class="dt">size_t</span> SumOfArity = zero + arity!fun;
}

<span class="kw">template</span> SumOfArities(F...)
{
    <span class="kw">alias</span> StaticScan!(SumOfArity, <span class="dv">0</span>, F) SumOfArities;
}

<span class="kw">template</span> SumOfReturn(<span class="dt">size_t</span> zero, <span class="kw">alias</span> fun)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(ReturnType!fun == <span class="dt">void</span>))
        <span class="kw">enum</span> <span class="dt">size_t</span> SumOfReturn = zero;
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">size_t</span> SumOfReturn = zero + <span class="dv">1</span>;
}

<span class="kw">template</span> SumOfReturns(Funs...)
{
    <span class="kw">alias</span> StaticScan!(SumOfReturn, <span class="dv">0</span>, Funs) SumOfReturns;
}</code></pre>
<p>Should I also add these?</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> maponalias;
<span class="kw">import</span> std.typetuple;

<span class="co">/**</span>
<span class="co"> * Maps the Mapper template on the alias list.</span>
<span class="co"> */</span>
<span class="kw">template</span> MapOnAlias(<span class="kw">alias</span> Mapper, <span class="kw">alias</span> current, Rest...)
{
    <span class="kw">static</span> <span class="kw">if</span> (Rest.<span class="dt">length</span>)
        <span class="kw">alias</span> TypeTuple!(Mapper!current, MapOnAlias!(Mapper, Rest)) MapOnAlias;
    <span class="kw">else</span>
        <span class="kw">alias</span> Mapper!current MapOnAlias;
}

<span class="kw">template</span> MapOnAlias(<span class="kw">alias</span> Mapper)
{
    <span class="kw">alias</span> TypeTuple!() MapOnAlias;
}</code></pre>
<h2 id="relational-algebra">Relational Algebra</h2>
<p>Inspiration for this example comes from <a href="http://david.rothlis.net/d/templates">This blog article</a>.</p>
<blockquote>
<p><strong>TODO</strong> I have the code somewhere. What it should do: extracting from a tuple: project, select. Also, natural/inner/outer join, cartesian product. And intersection/union/difference. <code>rename!(&quot;oldField&quot;, &quot;newField&quot;)</code>. Databases are just dynamic arrays of tuples.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> relational;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.typecons;
<span class="kw">import</span> std.range;
<span class="kw">import</span> std.conv;
<span class="kw">import</span> isastringliteral;
<span class="kw">import</span> istype;
<span class="kw">import</span> half;
<span class="kw">import</span> interleave;

<span class="kw">struct</span> Entry(Data...)
<span class="kw">if</span> ( (Data.<span class="dt">length</span> % <span class="dv">2</span> == <span class="dv">0</span>)
  &amp;&amp; (allSatisfy!(isAStringLiteral, Half!Data))
  &amp;&amp; (allSatisfy!(isType, Half!(Data[<span class="dv">1</span>..$], <span class="dt">void</span>))))
{
    <span class="kw">alias</span> Half!Data Headers;
    <span class="kw">alias</span> Half!(Data[<span class="dv">1</span>..$], <span class="dt">void</span>) Values;
    <span class="kw">alias</span> data <span class="kw">this</span>;

    Tuple!(Interleave!(Values).With!(Headers)) data;

    <span class="kw">this</span>(Values values)
    {
        <span class="kw">foreach</span>(i, Unused; Values) data[i] = values[i];
    }

    <span class="dt">string</span> toString() @property
    {
        <span class="dt">string</span> s = <span class="st">&quot;[&quot;</span>;
        <span class="kw">foreach</span>(i, Unused; Values)
            s ~= Headers[i] ~ <span class="st">&quot;:&quot;</span> ~ to!<span class="dt">string</span>(data[i]) ~ <span class="st">&quot;, &quot;</span>;
        <span class="kw">return</span> s[<span class="dv">0</span>..$-<span class="dv">2</span>] ~ <span class="st">&quot;]&quot;</span>;
    }
}

<span class="kw">template</span> entry(Headers...)
<span class="kw">if</span> (allSatisfy!(isAStringLiteral, Headers))
{
    Entry!(Interleave!(Headers).With!(Values)) entry(Values...)(Values values)
    <span class="kw">if</span> (Values.<span class="dt">length</span> == Headers.<span class="dt">length</span>)
    {
        <span class="kw">return</span> <span class="dt">typeof</span>(<span class="kw">return</span>)(values);
    }
}

<span class="kw">template</span> isEntry(E)
{
    <span class="kw">enum</span> isEntry = __traits(compiles,
                     {
                          <span class="dt">void</span> fun(T...)(Entry!T e) {}
                          fun(E.<span class="dt">init</span>);
                     });
}

<span class="kw">auto</span> rename(<span class="dt">string</span> from, <span class="dt">string</span> to, E)(E e)
<span class="kw">if</span> (isEntry!E)
{
    <span class="kw">enum</span> index = staticIndexOf!(from, E.Headers);
    <span class="kw">static</span> <span class="kw">if</span> (index == -<span class="dv">1</span>)
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">false</span>, <span class="st">&quot;Bad index in rename: no header called &quot;</span>
                             ~ from ~ <span class="st">&quot; in &quot;</span> ~ E.Headers.<span class="dt">stringof</span>);
    <span class="kw">else</span>
        <span class="kw">return</span> entry!(E.Headers[<span class="dv">0</span>..index],
                      to,
                      E.Headers[index+<span class="dv">1</span>..$])(e.data.expand);
}

<span class="kw">auto</span> rename(<span class="dt">string</span> from, <span class="dt">string</span> to, D)(D db)
<span class="kw">if</span> (isDatabase!D)
{
    ReturnType!(rename!(from, to, ElementType!D))[] result;
    <span class="kw">foreach</span>(i, elem; db)
        result ~= rename!(from, to)(elem);
    <span class="kw">return</span> result;
}


<span class="kw">template</span> isDatabase(D)
{
    <span class="kw">static</span> <span class="kw">if</span> (isDynamicArray!D &amp;&amp; isEntry!(ElementType!D))
        <span class="kw">enum</span> <span class="dt">bool</span> isDatabase = <span class="kw">true</span>;
    <span class="kw">else</span>
        <span class="kw">enum</span> <span class="dt">bool</span> isDatabase = <span class="kw">false</span>;
}

<span class="kw">template</span> isSomeHeader(E)
<span class="kw">if</span> (isEntry!E)
{
    <span class="kw">template</span> isSomeHeader(<span class="dt">string</span> s)
    {
        <span class="kw">static</span> <span class="kw">if</span> (staticIndexOf!(s, E.Headers) != -<span class="dv">1</span>)
            <span class="kw">enum</span> <span class="dt">bool</span> isSomeHeader = <span class="kw">true</span>;
        <span class="kw">else</span>
            <span class="kw">enum</span> <span class="dt">bool</span> isSomeHeader = <span class="kw">false</span>;
    }
}

<span class="kw">template</span> HeaderValue(E)
<span class="kw">if</span> (isEntry!E)
{
    <span class="kw">template</span> HeaderValue(<span class="dt">string</span> header)
    <span class="kw">if</span> (staticIndexOf!(header, E.Headers) != -<span class="dv">1</span>)
    {
        <span class="kw">alias</span> TypeTuple!(header, E.Values[staticIndexOf!(header, E.Headers)])
              HeaderValue;
    }
}

<span class="kw">template</span> project(Headers...)
<span class="kw">if</span> (Headers.<span class="dt">length</span> &gt; <span class="dv">0</span>)
{
    <span class="kw">auto</span> project(E)(E e)
    {
        <span class="kw">static</span> <span class="kw">if</span> (isEntry!E &amp;&amp; allSatisfy!(isSomeHeader!E, Headers))
        {
            <span class="kw">alias</span> staticMap!(HeaderValue!E, Headers)
                  HeadersAndValues;
            Entry!(HeadersAndValues) result;
            <span class="kw">foreach</span>(i, Unused; Headers)
                <span class="kw">mixin</span>(<span class="st">&quot;result.&quot;</span> ~ Headers[i] ~ <span class="st">&quot; = e.&quot;</span> ~ Headers[i] ~ <span class="st">&quot;;&quot;</span>);
            <span class="kw">return</span> result;
        }
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (isDatabase!E
                     &amp;&amp; allSatisfy!(isSomeHeader!(ElementType!E), Headers))
        {
            <span class="kw">alias</span> staticMap!(HeaderValue!(ElementType!E), Headers)
                  HeadersAndValues;

            Entry!(HeadersAndValues)[] result;
            Entry!(HeadersAndValues)   elem;

            <span class="kw">foreach</span>(i,Unused; e)
            {
                <span class="kw">foreach</span>(j, Unused2; Headers)
                    <span class="kw">mixin</span>(<span class="st">&quot;elem.&quot;</span> ~ Headers[j] ~ <span class="st">&quot; = e[i].&quot;</span> ~ Headers[j] ~ <span class="st">&quot;;&quot;</span>);
                result ~= elem;
            }
            <span class="kw">return</span> result;
        }
        <span class="kw">else</span>
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;Cannot project on &quot;</span> ~ Headers.<span class="dt">stringof</span>[<span class="dv">5</span>..$]
                           ~ <span class="st">&quot; for type &quot;</span> ~ E.<span class="dt">stringof</span>);
    }
}</code></pre>
<p><code class="sourceCode d">Half</code> is more or less the converse of <code class="sourceCode d">Interleave</code> (see section <a href="#interleaving-types">Interleaving Types</a>): given a typetuple, it takes every other types:<a href="#fn21" class="footnoteRef" id="fnref21"><sup>21</sup></a></p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> half;
<span class="kw">import</span> std.typetuple;

<span class="kw">template</span> Half(T...)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">alias</span> TypeTuple!() Half;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> == <span class="dv">1</span>)
        <span class="kw">alias</span> TypeTuple!(T[<span class="dv">0</span>]) Half;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!(T[<span class="dv">0</span>], Half!(T[<span class="dv">2</span>..$])) Half;
}

<span class="kw">unittest</span>
{
    <span class="kw">alias</span> TypeTuple!() Test0;
    <span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>) Test1;
    <span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">float</span>) Test2;
    <span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">float</span>, <span class="dt">string</span>) Test3;
    <span class="kw">alias</span> TypeTuple!(<span class="dt">int</span>, <span class="dt">float</span>, <span class="dt">string</span>, <span class="dt">double</span>) Test4;

    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Half!Test0 == TypeTuple!()));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Half!Test1 == TypeTuple!(<span class="dt">int</span>)));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Half!Test2 == TypeTuple!(<span class="dt">int</span>)));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Half!Test3 == TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>)));
    <span class="kw">static</span> <span class="kw">assert</span>(<span class="kw">is</span>(Half!Test4 == TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>)));
}</code></pre>
<p>Which gives us:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingrelational;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> relational;

<span class="kw">alias</span> Entry!(<span class="st">&quot;Name&quot;</span>,     <span class="dt">string</span>
            ,<span class="st">&quot;EmployId&quot;</span>, <span class="dt">int</span>
            ,<span class="st">&quot;Dept&quot;</span>, <span class="dt">string</span>) Employee;

<span class="kw">alias</span> Entry!(<span class="st">&quot;DeptName&quot;</span>, <span class="dt">string</span>
            ,<span class="st">&quot;Manager&quot;</span>,  <span class="dt">string</span>) Dept;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> e = entry!(<span class="st">&quot;Name&quot;</span>, <span class="st">&quot;EmployId&quot;</span>, <span class="st">&quot;DeptName&quot;</span>)(<span class="st">&quot;John&quot;</span>, <span class="dv">1</span>, <span class="st">&quot;Tech&quot;</span>);
    <span class="kw">auto</span> e2 = Employee(<span class="st">&quot;Susan&quot;</span>, <span class="dv">2</span>, <span class="st">&quot;Financial&quot;</span>);
    <span class="kw">auto</span> e3 = Employee(<span class="st">&quot;Bob&quot;</span>, <span class="dv">3</span>, <span class="st">&quot;Financial&quot;</span>);
    <span class="kw">auto</span> e4 = Employee(<span class="st">&quot;Sri&quot;</span>, <span class="dv">4</span>, <span class="st">&quot;Tech&quot;</span>);

    <span class="kw">auto</span> d1 = Dept(<span class="st">&quot;Tech&quot;</span>, <span class="st">&quot;Sri&quot;</span>);
    <span class="kw">auto</span> d2 = Dept(<span class="st">&quot;Financial&quot;</span>, <span class="st">&quot;Bob&quot;</span>);

    <span class="kw">auto</span> employees = [e2,e3,e4];
    <span class="kw">auto</span> depts = [d1, d2];

    writeln(employees);

    writeln(rename!(<span class="st">&quot;Dept&quot;</span>, <span class="st">&quot;DN&quot;</span>)(employees));
}</code></pre>
<h2 id="fun-with-classes-and-structs">Fun With Classes and Structs</h2>
<h3 id="class-hierarchy">Class Hierarchy</h3>
<blockquote>
<p><strong>Unfinished</strong> Two things I'll show here: how to get a class parents an how to determine an entire hierarchy of classes in a local scope.</p>
</blockquote>
<h3 id="generic-maker-function">Generic Maker Function</h3>
<p>Like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">class</span> C
{
    <span class="dt">int</span> i, j;

    <span class="kw">this</span>(<span class="dt">int</span> _i) { i = _i; j = _i;}
    <span class="kw">this</span>(<span class="dt">int</span> _i, <span class="dt">int</span> _j) { i = _i; j =_j;}
}

<span class="kw">alias</span> make!C makeC;

<span class="kw">auto</span> theCs = map!makeC([<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>]);
<span class="kw">auto</span> theCs2 = map!makeC(zip([<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>,<span class="dv">4</span>],
                            [<span class="dv">4</span>,<span class="dv">3</span>,<span class="dv">2</span>,<span class="dv">1</span>,<span class="dv">0</span>]));</code></pre>
<h2 id="emitting-events">Emitting Events</h2>
<p>This example template, comprising <code class="sourceCode d">Fields</code> and <code class="sourceCode d">Notify</code>, comes from Andrej Mitrovic. He has be kind enough to allow me to put it there and to give me some explanations for the logic behind this template. He's using it in his experimental GUI library to signal an event.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> fields;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> isastringliteral;

<span class="kw">mixin</span> <span class="kw">template</span> Fields(T, fields...)
    <span class="kw">if</span> (allSatisfy!(isAStringLiteral, fields))
{
    <span class="kw">alias</span> <span class="dt">typeof</span>(<span class="kw">this</span>) This;

    <span class="kw">static</span> <span class="dt">string</span> __makeFields(T, fields...)()
    {
        <span class="dt">string</span> res;
        <span class="kw">foreach</span>(field; fields) res ~= T.<span class="dt">stringof</span>~ <span class="st">&quot; &quot;</span> ~ field ~ <span class="st">&quot;;\n&quot;</span>;
        <span class="kw">return</span> res;
    }

    <span class="kw">static</span> <span class="dt">string</span> __makeOpBinaryFields(<span class="dt">string</span> op, fields...)()
    {
        <span class="dt">string</span> res;
        <span class="kw">foreach</span>(field; fields)
            res ~= <span class="st">&quot;res.&quot;</span> ~ field
                 ~ <span class="st">&quot; = this.&quot;</span> ~ field ~ op ~ <span class="st">&quot; rhs.&quot;</span> ~ field ~ <span class="st">&quot;;\n&quot;</span>;
        <span class="kw">return</span> res;
    }

    <span class="kw">mixin</span>(__makeFields!(T, fields)());

    This opBinary(<span class="dt">string</span> op)(This rhs)
    {
        This res;
        <span class="kw">mixin</span>(__makeOpBinaryFields!(op, fields)());
        <span class="kw">return</span> res;
    }

    <span class="dt">void</span> opOpAssign(<span class="dt">string</span> op)(This rhs)
    {
        <span class="kw">mixin</span>(<span class="st">&quot;this = this &quot;</span> ~ op ~ <span class="st">&quot; rhs;&quot;</span>);
    }
}</code></pre>
<p>The user mix it in its own types:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingfields;
<span class="kw">import</span> fields;

<span class="kw">struct</span> Point {
    <span class="kw">mixin</span> Fields!(<span class="dt">int</span>, <span class="st">&quot;x&quot;</span>, <span class="st">&quot;y&quot;</span>, <span class="st">&quot;z&quot;</span>, <span class="st">&quot;w&quot;</span>);
}

<span class="kw">struct</span> Size {
    <span class="kw">mixin</span> Fields!(<span class="dt">int</span>, <span class="st">&quot;width&quot;</span>, <span class="st">&quot;height&quot;</span>);
}</code></pre>
<p>This goes hand in hand with the <code class="sourceCode d">Notify</code> struct template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> notify;
<span class="kw">import</span> std.conv;

<span class="kw">struct</span> Notify(T)
{
    <span class="kw">alias</span> <span class="dt">void</span> <span class="kw">delegate</span>(<span class="kw">ref</span> T) OnEventFunc;
    OnEventFunc onEvent;

    <span class="dt">void</span> init(OnEventFunc func) {
        onEvent = func;
    }

    <span class="dt">string</span> toString()
    {
        <span class="kw">return</span> to!<span class="dt">string</span>(raw);
    }

    <span class="kw">auto</span> opEquals(T)(T rhs)
    {
        <span class="kw">return</span> rhs == rhs;
    }

    <span class="dt">void</span> opAssign(T)(T rhs)
    {
        <span class="kw">if</span> (rhs == raw)
            <span class="kw">return</span>;  <span class="co">// avoid infinite loops</span>

        <span class="co">// temp used for ref</span>
        <span class="kw">auto</span> temp = rhs;
        onEvent(temp);
    }

    <span class="kw">auto</span> opBinary(<span class="dt">string</span> op, T)(T rhs)
    {
        <span class="kw">mixin</span>(<span class="st">&quot;return raw &quot;</span> ~ op ~ <span class="st">&quot; rhs;&quot;</span>);
    }

    <span class="dt">void</span> opOpAssign(<span class="dt">string</span> op, T)(T rhs)
    {
        <span class="co">// temp used for ref</span>
        <span class="kw">mixin</span>(<span class="st">&quot;auto temp = raw &quot;</span> ~ op ~ <span class="st">&quot; rhs;&quot;</span>);

        <span class="kw">if</span> (temp == raw)
            <span class="kw">return</span>;  <span class="co">// avoid infinite loops</span>

        onEvent(temp);
    }

    <span class="kw">public</span> T raw;  <span class="co">// raw access when we don&#39;t want to invoke event()</span>
    <span class="kw">alias</span> raw <span class="kw">this</span>;
}</code></pre>
<p>Which you mix in classes you want to notify any changes to their internal state:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingnotify;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> usingfields;
<span class="kw">import</span> notify;

<span class="kw">class</span> Widget
{
    <span class="kw">this</span>()
    {
        point.<span class="dt">init</span>((<span class="kw">ref</span> Point pt) { writefln(<span class="st">&quot;changed point to %s&quot;</span>, pt); });
        size.<span class="dt">init</span>((<span class="kw">ref</span> Size sz)   { writefln(<span class="st">&quot;changed size to %s&quot;</span>, sz); });
    }

    Notify!Point point;
    Notify!Size size;
}</code></pre>
<p>For example, a user might change the point (position) field of a widget via:</p>
<pre class="sourceCode d"><code class="sourceCode d">Point moveBy = Point(<span class="dv">10</span>, <span class="dv">0</span>); widget.point += moveBy;}.</code></pre>
<p>This doesn't modify the field yet, but only triggers <code class="sourceCode d">onEvent(moveBy)</code>, which in turn emits a signal containing the <code class="sourceCode d">Widget</code> reference and the requested position <code class="sourceCode d">doMove.emit(<span class="kw">this</span>, moveBy)</code>. This gets processed by a chain of an arbitrary number of listeners. These listeners take <code class="sourceCode d">moveBy</code> by reference and this comes in handy when e.g. a <code class="sourceCode d">Widget</code> is part of a <code class="sourceCode d">Layout</code>. The <code class="sourceCode d">Layout</code> simply adds itself to the chain of listeners and edits the ref argument if it wants to, or even returns <code class="sourceCode d"><span class="kw">false</span></code> to completely deny any changes to a field.</p>
<p>This allows for some great flexibility. For example, say a user subclasses from <code class="sourceCode d">Widget</code> (let's call it <code class="sourceCode d">Child</code>), and overrides <code class="sourceCode d">onMove()</code> of the widget to limit it to the position of:</p>
<pre class="sourceCode d"><code class="sourceCode d">min: Point(<span class="dv">10</span>, <span class="dv">10</span>) (top-left)
max: Point(<span class="dv">100</span>, <span class="dv">100</span>) (bottom-right)</code></pre>
<p>This <code class="sourceCode d">Widget</code> has a parent <code class="sourceCode d">Widget</code> (call it <code class="sourceCode d">Parent</code>), which has a layout set. The layout might allow any child <code class="sourceCode d">Widget</code>s of the <code class="sourceCode d">Parent</code> to only be set between the following positions:</p>
<pre class="sourceCode d"><code class="sourceCode d">min: Point(<span class="dv">20</span>, <span class="dv">20</span>)
max: Point(<span class="dv">80</span>, <span class="dv">80</span>)</code></pre>
<p>Additionally the layout might take a child's size into account so the <code class="sourceCode d">Widget</code> never overflows the <code class="sourceCode d">min</code> and <code class="sourceCode d">max</code> points of the layout. If this <code class="sourceCode d">Widget</code> was at <code class="sourceCode d">Point(<span class="dv">20</span>, <span class="dv">20</span>)</code> and had <code class="sourceCode d">Size(<span class="dv">50</span>, <span class="dv">50</span>)</code> it means the layout will limit the <code class="sourceCode d">Wid\-get</code>'s minimum and maximum points to:</p>
<pre class="sourceCode d"><code class="sourceCode d">min: Point(<span class="dv">20</span>, <span class="dv">20</span>)
max: Point(<span class="dv">30</span>, <span class="dv">30</span>)</code></pre>
<p>When the <code class="sourceCode d">Widget</code> is at <code class="sourceCode d">Point(<span class="dv">30</span>, <span class="dv">30</span>)</code> its bottom-right point will be <code class="sourceCode d">Point(<span class="dv">80</span>, <span class="dv">80</span>)</code>, which is the maximum bottom-right point the layout has set. The layout won't allow the <code class="sourceCode d">Widget</code> to be at position <code class="sourceCode d">Point(<span class="dv">10</span>, <span class="dv">10</span>)</code> either, even though <code class="sourceCode d">Widget</code>'s <code class="sourceCode d">onMove</code> method allows it.</p>
<p>So if the user tries to call:</p>
<pre class="sourceCode d"><code class="sourceCode d">child.point = Point(<span class="dv">120</span>, <span class="dv">120</span>);</code></pre>
<p>First, <code class="sourceCode d">Child</code>'s <code class="sourceCode d">onMove</code> is the first listener of some <code class="sourceCode d">doMove</code> signal. It will modify the ref argument and set it to <code class="sourceCode d">Point(<span class="dv">100</span>, <span class="dv">100</span>)</code> as the user coded it that way. Then, the layout will modify it to <code class="sourceCode d">Point(<span class="dv">30</span>, <span class="dv">30</span>)</code> since it takes <code class="sourceCode d">Widget</code>'s size into account so it doesn't overflow.</p>
<p>There could be any number of listeners, and you could add a listener to any position in the chain of events (maybe you want to intercept and modify the argument before it reaches <code class="sourceCode d">Parent</code>'s layout if you want to set temporary limits to a <code class="sourceCode d">Widget</code>'s position).</p>
<p>Finally, there is always one last listener. This one is an internal function that actually modifies the <code class="sourceCode d">.raw</code> field, and calls into internal painting and blitting functions to make the <code class="sourceCode d">Widget</code> appear into its new position. Also, any listener can return <code class="sourceCode d"><span class="kw">false</span></code> to break further processing of events and deny modifying the field.</p>
<p>Notice that assignments never happen, external code has to use the <code class="sourceCode d">.raw</code> field to actually modify the internal payload, which avoids calling <code class="sourceCode d">onEvent()</code>.</p>
<h2 id="fields">Fields</h2>
<p>From Jacob Carlborg's <a href="https://github.com/jacob-carlborg/orange">Orange</a> serialization library:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> fieldsof;

<span class="co">/**</span>
<span class="co"> * Evaluates to an array of strings containing</span>
<span class="co"> * the names of the fields in the given type</span>
<span class="co"> */</span>
<span class="kw">template</span> fieldsOf (T)
{
    <span class="kw">const</span> fieldsOf = fieldsOfImpl!(T, <span class="dv">0</span>);
}

<span class="co">/**</span>
<span class="co"> * Implementation for fieldsOf</span>
<span class="co"> *</span>
<span class="co"> * Returns: an array of strings containing the names of the fields in the given type</span>
<span class="co"> */</span>
<span class="kw">template</span> fieldsOfImpl (T, <span class="dt">size_t</span> i)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">tupleof</span>.<span class="dt">length</span> == <span class="dv">0</span>)
        <span class="kw">enum</span> fieldsOfImpl = [<span class="st">&quot;&quot;</span>];

    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">tupleof</span>.<span class="dt">length</span> - <span class="dv">1</span> == i)
        <span class="kw">enum</span> fieldsOfImpl = [T.<span class="dt">tupleof</span>[i].<span class="dt">stringof</span>[<span class="dv">1</span> + T.<span class="dt">stringof</span>.<span class="dt">length</span> + <span class="dv">2</span> .. $]];

    <span class="kw">else</span>
        <span class="kw">enum</span> fieldsOfImpl = T.<span class="dt">tupleof</span>[i].<span class="dt">stringof</span>[<span class="dv">1</span> + T.<span class="dt">stringof</span>.<span class="dt">length</span> + <span class="dv">2</span> .. $] ~ fieldsOfImpl!(T, i + <span class="dv">1</span>);
}</code></pre>
<h2 id="extending-an-enum">Extending an enum</h2>
<p>This code comes from Simen Kjaeras. It generates an enum definition as a string, by taking all the members of the old enum, and adding those passed in string parameters, and mixing it in.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> enumdefasstring;

<span class="dt">string</span> EnumDefAsString(T)()
<span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">enum</span>))
{
   <span class="dt">string</span> result = <span class="st">&quot;&quot;</span>;
   <span class="kw">foreach</span> (e; __traits(allMembers, T))
       result ~= e ~ <span class="st">&quot; = T.&quot;</span> ~ e ~ <span class="st">&quot;,&quot;</span>;
   <span class="kw">return</span> result;
}</code></pre>
<p>This piece of code iterates over all members of the passed <code class="sourceCode d"><span class="kw">enum</span></code><code class="sourceCode d">T</code>, generating a string containing all members and their values. For this enum:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">enum</span> bar
{
    a, b, c
}</code></pre>
<p>The generated string looks like this (if you want to check this, feel free to call <code class="sourceCode d">EnumDefAsString</code> at run-time and print its result):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="st">&quot;a = bar.a,b = bar.b,c = bar.c&quot;</span></code></pre>
<p>As we can see, this is a valid body for an enum. That means we can use <code class="sourceCode d"><span class="kw">mixin</span></code><code class="sourceCode d">()</code> to generate this exact same enum. But wait - there's more:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> extendenum;
<span class="kw">import</span> enumdefasstring;

<span class="kw">template</span> ExtendEnum(T, <span class="dt">string</span> s)
   <span class="kw">if</span> (<span class="kw">is</span>(T == <span class="kw">enum</span>) &amp;&amp;
   <span class="kw">is</span>(<span class="dt">typeof</span>({<span class="kw">mixin</span>(<span class="st">&quot;enum a{&quot;</span>~s~<span class="st">&quot;}&quot;</span>);})))
{
   <span class="kw">mixin</span>(
   <span class="st">&quot;enum ExtendEnum {&quot;</span>
   ~ EnumDefAsString!T()
   ~ s
   ~ <span class="st">&quot;}&quot;</span>);
}</code></pre>
<p>This code concatenates the string generated from the previous function with the one passed to the function as parameter <code>s</code>. So with <code class="sourceCode d">bar</code> previously defined, and this instantiation:</p>
<pre class="sourceCode d"><code class="sourceCode d">ExtendEnum!(bar, <span class="st">&quot;d=25&quot;</span>)</code></pre>
<p>The body of the function will look like this (after string expansion):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">mixin</span>(
   <span class="st">&quot;enum ExtendEnum {&quot;</span>
   ~ <span class="st">&quot;a = bar.a,b = bar.b,c = bar.c&quot;</span>
   ~ <span class="st">&quot;d=25&quot;</span>
   ~ <span class="st">&quot;}&quot;</span>);</code></pre>
<p>Concatenating those strings, we see that we have a valid enum definition:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">enum</span> ExtendEnum {a = bar.a,b = bar.b,c = bar.c,d=<span class="dv">25</span>}</code></pre>
<p>The mixin then pastes it in, and it is compiled as regular D code.</p>
<h2 id="static-switching">Static Switching </h2>
<blockquote>
<p><strong>TODO</strong> What, no compile-time switch? Let's create one. Example of: tuples, type filtering (in constraints), recursion, etc.</p>
</blockquote>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> staticswitch;

<span class="kw">template</span> staticSwitch(List...) <span class="co">// List[0] is the value commanding the switching</span>
                               <span class="co">// It can be a type or a symbol.</span>
{
    <span class="kw">static</span> <span class="kw">if</span> (List.<span class="dt">length</span> == <span class="dv">1</span>) <span class="co">// No slot left: error</span>
        <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;StaticSwitch: no match for &quot;</span> ~ List[<span class="dv">0</span>].<span class="dt">stringof</span>);
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (List.<span class="dt">length</span> == <span class="dv">2</span>) <span class="co">// One slot left: default case</span>
        <span class="kw">enum</span> staticSwitch = List[<span class="dv">1</span>];
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(List[<span class="dv">0</span>] == List[<span class="dv">1</span>]) <span class="co">// Comparison on types</span>
                || (  !<span class="kw">is</span>(List[<span class="dv">0</span>])         <span class="co">// Comparison on values</span>
                   &amp;&amp; !<span class="kw">is</span>(List[<span class="dv">1</span>])
                   &amp;&amp; <span class="kw">is</span>(<span class="dt">typeof</span>(List[<span class="dv">0</span>] == List[<span class="dv">1</span>]))
                   &amp;&amp; (List[<span class="dv">0</span>] == List[<span class="dv">1</span>])))
        <span class="kw">enum</span> staticSwitch = List[<span class="dv">2</span>];
    <span class="kw">else</span>
        <span class="kw">enum</span> staticSwitch = staticSwitch!(List[<span class="dv">0</span>], List[<span class="dv">3</span>..$]);
}</code></pre>
<h2 id="generic-structures">Generic Structures</h2>
<blockquote>
<p><strong>Unfinished</strong> This section will present some generic structures of growing complexity.</p>
</blockquote>
<h3 id="gobble">Gobble</h3>
<p>Let's begin with <code class="sourceCode d">Gobbler</code>, a small exercise in tuple manipulation and operator overloading. <code class="sourceCode d">Gobbler</code> is a struct wrapping a tuple and defining only one operator: the right-concatenation operator (<code class="sourceCode d">\~</code>).</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> gobbler;

<span class="kw">struct</span> Gobbler(T...)
{
    <span class="kw">alias</span> T Types;
    T store;
    Gobbler!(T, U) opBinary(<span class="dt">string</span> op, U)(U u) <span class="kw">if</span> (op == <span class="st">&quot;~&quot;</span>)
    {
        <span class="kw">return</span> Gobbler!(T, U)(store, u);
    }
}

Gobbler!() gobble() { <span class="kw">return</span> Gobbler!()();}</code></pre>
<p><code class="sourceCode d">gobble</code> creates an empty gobbler and is there to activate the aspiration:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usinggobbler;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> gobbler;

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> list = gobble ~ <span class="dv">1</span> ~ <span class="st">&quot;abc&quot;</span> ~ <span class="fl">3.14</span> ~ <span class="st">&quot;another string!&quot;</span>;
    <span class="kw">assert</span>(<span class="kw">is</span>(list.Types == TypeTuple!(<span class="dt">int</span>, <span class="dt">string</span>, <span class="dt">double</span>, <span class="dt">string</span>)));
    <span class="kw">assert</span>(list.store[<span class="dv">2</span>] == <span class="fl">3.14</span>);
}</code></pre>
<blockquote>
<p><strong>TODO</strong> Indexing the <code class="sourceCode d">Gobbler</code>.</p>
</blockquote>
<h3 id="polymorphic-association-lists">Polymorphic Association Lists</h3>
<p>An association list as a sort of 'flat' associative array: it holds key-value pairs in a linear list. A polymorphic (aka, templated) one is a tuple holding a bunch of key-value keys, but with more flexibility on the types for keys and values. Different trade-off can be done here between the runtime or compile-time nature of keys and values.</p>
<blockquote>
<p><strong>Unfinished</strong> This section will present one solution.</p>
</blockquote>
<p>Usage: a bit like Lua tables: structs, classes (you can put anonymous functions in them?), namespaces. Also, maybe to add metadata to a type?</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> alist;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> half;

<span class="kw">struct</span> AList(T...)
{
    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> &gt;= <span class="dv">2</span> &amp;&amp; T.<span class="dt">length</span> % <span class="dv">2</span> == <span class="dv">0</span>)
        <span class="kw">alias</span> Half!T Keys;
    <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> &gt;= <span class="dv">2</span> &amp;&amp; T.<span class="dt">length</span> % <span class="dv">2</span> == <span class="dv">1</span>)
        <span class="kw">alias</span> Half!(T[<span class="dv">0</span>..$-<span class="dv">1</span>]) Keys;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!() Keys;

    <span class="kw">static</span> <span class="kw">if</span> (T.<span class="dt">length</span> &gt;= <span class="dv">2</span>)
        <span class="kw">alias</span> Half!(T[<span class="dv">1</span>..$]) Values;
    <span class="kw">else</span>
        <span class="kw">alias</span> TypeTuple!() Values;

    <span class="kw">template</span> at(<span class="kw">alias</span> a)
    {
        <span class="co">// key not found, but default value present</span>
        <span class="kw">static</span> <span class="kw">if</span> ((staticIndexOf!(a, Keys) == -<span class="dv">1</span>) &amp;&amp; (T.<span class="dt">length</span> % <span class="dv">2</span> == <span class="dv">1</span>))
            <span class="kw">enum</span> at = T[$-<span class="dv">1</span>]; <span class="co">// default value</span>
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> ((staticIndexOf!(a, Keys) == -<span class="dv">1</span>) &amp;&amp; (T.<span class="dt">length</span> % <span class="dv">2</span> == <span class="dv">0</span>))
            <span class="kw">static</span> <span class="kw">assert</span>(<span class="dv">0</span>, <span class="st">&quot;AList: no key equal to &quot;</span> ~ a.<span class="dt">stringof</span>);
        <span class="kw">else</span> <span class="co">//static if (Keys[staticIndexOf!(a, Keys)] == a)</span>
            <span class="kw">enum</span> at = Values[staticIndexOf!(a, Keys)];
    }
}

<span class="dt">void</span> main()
{
    <span class="kw">alias</span> AList!( <span class="dv">1</span>,     <span class="st">&quot;abc&quot;</span>
                , <span class="dv">2</span>,     <span class="ch">&#39;d&#39;</span>
                , <span class="dv">3</span>,     <span class="st">&quot;def&quot;</span>
                , <span class="st">&quot;foo&quot;</span>, <span class="fl">3.14</span>
                ,        <span class="st">&quot;Default&quot;</span>) al;

    writeln(<span class="st">&quot;Keys: &quot;</span>, al.Keys.<span class="dt">stringof</span>);
    writeln(<span class="st">&quot;Values: &quot;</span>, al.Values.<span class="dt">stringof</span>);
    writeln(<span class="st">&quot;at!1: &quot;</span>, al.at!(<span class="dv">1</span>));
    writeln(<span class="st">&quot;at!2: &quot;</span>, al.at!(<span class="dv">2</span>));
    writeln(<span class="st">&quot;at!\&quot;foo\&quot;: &quot;</span>, al.at!(<span class="st">&quot;foo&quot;</span>));
    writeln(<span class="st">&quot;Default: &quot;</span>, al.at!<span class="dv">4</span>);
}</code></pre>
<h3 id="a-polymorphic-tree">A Polymorphic Tree</h3>
<p>So, what's a polymorphic tree? It's just a tuple hoding other tuples as elements, as a standard tree container, only all values can be of a different type. Obviously this means that trees holding values of different types will also be of a different type, since the entire content's type is part of the tree signature. It can be a bit baffling to see one, but with a few helper functions to transform a tree or extract some values, it can be quite interesting to use.</p>
<p>Just to get a little feel for them and to use a less-used example for trees, imagine wanting to manipulate mark-up text in D. You could create your document as a D structure and then invoke some functions to transform it into DDoc text, or a LaTeX document, a Markdown one or even HTML:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">auto</span> doc =
document(
    title(<span class="st">&quot;Ranges: A Tutorial&quot;</span>),
    author(<span class="st">&quot;John Doe&quot;</span>),
    tableOfContents,

    <span class="co">/* level-one section */</span>
    section!<span class="dv">1</span>(
        title(<span class="st">&quot;Some Range Definitions&quot;</span>),
        <span class="st">&quot;Ranges are a nice D abstraction...&quot;</span>,
        definition(
            <span class="st">&quot;Input Range&quot;</span>,
            <span class="st">&quot;The most basic kind of range, it must define the following methods:&quot;</span>,
            list(definition(<span class="st">&quot;front&quot;</span>, <span class="st">&quot;...&quot;</span>),
                 definition(<span class="st">&quot;popFront&quot;</span>, <span class="st">&quot;...&quot;</span>),
                 definition(<span class="st">&quot;empty&quot;</span>, <span class="st">&quot;...&quot;</span>))
        )
    )
    section!<span class="dv">1</span>(
        title(<span class="st">&quot;Some ranges examples&quot;</span>),
        <span class="st">&quot;...&quot;</span>,
        code(
            <span class="st">&quot;auto m = map!((a) =&gt; a*a)([0,1,2,3]);</span>
<span class="st">             assert(m.length == 4);&quot;</span>
        ),
        link(<span class="st">&quot;http://dlang.org/&quot;</span>, <span class="st">&quot;Website&quot;</span>)
    )
    section!<span class="dv">1</span>(
        title(<span class="st">&quot;Beyond ranges&quot;</span>),
        <span class="st">&quot;...&quot;</span>
    )
);

<span class="kw">auto</span> latex = doc.to!<span class="st">&quot;LaTeX&quot;</span>;
<span class="kw">auto</span> html = doc.to!<span class="st">&quot;HTML&quot;</span>;
<span class="kw">auto</span> ddoc = doc.to!<span class="st">&quot;Ddoc&quot;</span>;
<span class="kw">auto</span> simple = doc.to!<span class="st">&quot;text&quot;</span>;</code></pre>
<p>In the previous (imaginary, but tempting for me) code, <code class="sourceCode d">doc</code> is a tuple made by the <code class="sourceCode d">document</code> factory function and holding small specifically marked pieces of text: <code class="sourceCode d">title</code>, <code class="sourceCode d">section</code> or <code class="sourceCode d">link</code>. Each is a factory function producing a user-defined struct following a few simple conventions. If all types have a <code class="sourceCode d">to!<span class="st">&quot;HTML&quot;</span></code> member that transforms their content into HTML code, then the entire document can be dumped as a HTML file. The different types need not be classes inheriting from a common base and that must be shoe-horned into a defined hierarchy: <a href="#constraints">template constraints</a> do the verification for you. Think ranges.</p>
<p>This is an example of a polymorphic tree.</p>
<h3 id="expression-templates">Expression Templates</h3>
<p>Expression templates are a kind of polymorphic tree, but restricted to some known operations (most of the times unary/binary/ternary operators) and their operands. It allows one to store for example an arithmetic operation like this:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// From &quot;x + 1 * y&quot;:</span>
Binary!(<span class="st">&quot;+&quot;</span>,
             Variable!<span class="st">&quot;x&quot;</span>,
             Binary!(<span class="st">&quot;*&quot;</span>,
                         Constant(<span class="dv">1</span>),
                         Variable!<span class="st">&quot;y&quot;</span>))</code></pre>
<p>The advantages are that you can then manipulate the resulting tree to simplify the expression or avoid temporary evaluations. The previous expression could be simplified to hold the equivalent of <code class="sourceCode d">x + y</code> (getting rid of the multiplication by one.</p>
<p>More generally, you can encode a programming language expression in such a tree:</p>
<pre class="sourceCode d"><code class="sourceCode d">AST!<span class="st">&quot;</span>
<span class="st">if (x == 0)</span>
<span class="st">then</span>
<span class="st">{</span>
<span class="st">    writeln(x);</span>
<span class="st">}</span>
<span class="st">else</span>
<span class="st">{</span>
<span class="st">    ++x;</span>
<span class="st">    foo(x,y);</span>
<span class="st">}&quot;</span>
=&gt;
If(Comparison!(<span class="st">&quot;==&quot;</span>, Symbol!<span class="st">&quot;x&quot;</span>, value(<span class="dv">0</span>)), <span class="co">// Condition</span>
<span class="co">// then branch</span>
   Block!( FunctionCall!(<span class="st">&quot;writeln&quot;</span>, Symbol!<span class="st">&quot;x&quot;</span>) ),
<span class="co">// (optional) else branch</span>
   Block!( Unary!(<span class="st">&quot;++&quot;</span>, Symbol!<span class="st">&quot;x&quot;</span>),
           FunctionCall!(<span class="st">&quot;foo&quot;</span>, Symbol!<span class="st">&quot;x&quot;</span>, Symbol!<span class="st">&quot;y&quot;</span>)))</code></pre>
<p>This way lies madness and the power of macros, because you can then manipulate the resulting Abstract Syntax Tree in any way you wish, rewrite the code it represents, convert it back into a string and write it into the file that will be given to the compiler.</p>
<p>So,</p>
<ul>
<li>Define a compile-time parser,</li>
<li>feed it (a reasonable part of) the D grammar,</li>
<li>define some new authorized constructs and the associated AST and the way this new constructs can be behind-the-scene assembled from existing part of the D language (aka, macros),</li>
<li>write code in your new D extension, your <em>precious</em>,</li>
<li>feed it with the macros to a program that will create the resulting AST, modifying it like you wish and reassemble it into <em>bona fide</em> D code.</li>
<li>and will then feed it to the standard D compiler.</li>
</ul>
<p>And <em>voila</em>, your own toy D extension. Or, you know, you could just bug Walter till he adds the syntax you want into the language.</p>
<h2 id="statically-checked-writeln">Statically-Checked Writeln</h2>
<p>This is an example of verifying a Domain-Specific Language (DSL) at compile-time in D. The goal is to take a format string for <a href="http://dlang.org/phobos/std_stdio.html#writef">std.stdio.writef</a> or <a href="http://dlang.org/phobos/std_stdio.html#writefln">std.stdio.writefln</a> and to check the arguments' types before passing them to <code class="sourceCode d">writef</code>(<code class="sourceCode d">ln</code>).</p>
<p>For example, when writing:</p>
<pre class="sourceCode d"><code class="sourceCode d">writefln(<span class="st">&quot;For sample #%d, the results are (%s, %f)&quot;</span>, num, name, f);</code></pre>
<p>We know that <code class="sourceCode d">%d</code> means the argument must be an integral type, <code class="sourceCode d">%f</code> asks for a floating-point type and so on. That means in the previous sample, we know that:</p>
<ul>
<li>There must exactly 3 args, no more, no less.</li>
<li>The first one must have an integral type.</li>
<li>The second one can be of any type (more exactly, of any type that can be converted into a <code class="sourceCode d"><span class="dt">string</span></code>).</li>
<li>The third one must be of some floating point type.</li>
</ul>
<p>These four conditions can be checked at compile-time, that's what we will do here. I won't code the entire POSIX specification for <code class="sourceCode d">printf</code>, the following table shows what will be checked.</p>
<table>
<caption>Standard formatters recognized by <code>cwritef</code></caption>
<thead>
<tr class="header">
<th align="left">Formatter</th>
<th align="left">Asks For</th>
<th align="left">Equivalent Constraint</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>%d</code>, <code>%i</code></td>
<td align="left">an integral type</td>
<td align="left"><code>isIntegral</code></td>
</tr>
<tr class="even">
<td align="left"><code>%u</code>, <code>%x</code>, <code>%X</code>, <code>%o</code></td>
<td align="left">an unsigned integral type</td>
<td align="left"><code>isUnsigned</code></td>
</tr>
<tr class="odd">
<td align="left"><code>%f</code>, <code>%F</code>, <code>%e</code>,</td>
<td align="left">a floating point type</td>
<td align="left"><code>isFloatingPoint</code></td>
</tr>
<tr class="even">
<td align="left"><code>%E</code>, <code>%g</code>, <code>%G</code></td>
<td align="left"></td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left"><code>%c</code></td>
<td align="left">a char type</td>
<td align="left"><code>isSomeChar</code></td>
</tr>
<tr class="even">
<td align="left"><code>%s</code></td>
<td align="left">any type</td>
<td align="left"><code>isAnyType</code></td>
</tr>
<tr class="odd">
<td align="left"><code>%%</code></td>
<td align="left">not a formatter</td>
<td align="left">no check</td>
</tr>
</tbody>
</table>
<p>For those interested in the details, <a href="http://en.wikipedia.org/wiki/Printf_format_string">this Wikipedia article</a> makes for a nice reference. Note that not all formatters are implemented in <a href="http://dlang.org/phobos/std_stdio.html">std.stdio</a>, for example the <code class="sourceCode d">%p</code> formatter for <code>void*</code> pointers seems not to work.</p>
<p>Most of the previous typechecking templates are in <a href="http://dlang.org/phobos/std_traits.html">std.traits</a>: <code class="sourceCode d">isIntegral</code>, <code class="sourceCode d">isFloatingPoint</code>, <code class="sourceCode d">isUnsigned</code> and <code class="sourceCode d">isSomeChar</code> are already implented in Phobos. The only one left is <code class="sourceCode d">isAnyType</code>, a quite complacent template:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> isanytype;

<span class="kw">template</span> isAnyType(T)
{
    <span class="kw">enum</span> isAnyType = <span class="kw">true</span>;
}</code></pre>
<p>The only way for it to fail would be to give it a non-type.</p>
<p>Continuing with the previous chapters' example-driven development, here is what I want to obtain (<code class="sourceCode d">cwritefln</code> stands for checked-<code class="sourceCode d">writefln</code>):</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> usingcheckedwrite;
<span class="kw">import</span> checkedwrite;

<span class="dt">void</span> main()
{
    cwritefln!<span class="st">&quot;For sample #%d, the results are (%s, %f)&quot;</span>( <span class="dv">0</span>, <span class="st">&quot;foo&quot;</span>, <span class="fl">3.14</span>); <span class="co">// OK</span>

 <span class="co">// NOK: bad number or args: waited for 3 args, got 2.</span>
 <span class="co">// cwritefln!&quot;For sample #%d, the results are (%s, %f)&quot;( 0, &quot;foo&quot;);</span>

 <span class="co">// NOK: arg #3 of type double does not verify check isFloatingPoint</span>
 <span class="co">// cwritefln!&quot;For sample #%d, the results are (%s, %f)&quot;( 0, 3.14, &quot;foo&quot;);</span>
}</code></pre>
<p>Now, given a formatting string, the first thing is to extract the formatters and construct the constraints list. Here I'll use a string mixin and just need to build a string representing the desired final code:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> getformatters;
<span class="kw">import</span> std.conv;
<span class="kw">import</span> std.traits;

<span class="dt">string</span> getFormatters(S)(S s) <span class="kw">if</span> (isSomeString!S)
{
    <span class="dt">dstring</span> ds = to!<span class="dt">dstring</span>(s);
    <span class="dt">bool</span> afterPercent = <span class="kw">false</span>;
    <span class="dt">bool</span> error;
    <span class="dt">string</span> result = <span class="st">&quot;alias TypeTuple!(&quot;</span>;
    <span class="kw">foreach</span>(elem; ds)
    {
        <span class="kw">if</span> (error) <span class="kw">break</span>;
        <span class="kw">if</span> (afterPercent)
        {
            <span class="kw">switch</span> (elem)
            {
                <span class="kw">case</span> <span class="ch">&#39;%&#39;</span>:
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="kw">case</span> <span class="ch">&#39;d&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;i&#39;</span>:
                    result ~= <span class="st">&quot;isIntegral,&quot;</span>; <span class="co">// integers</span>
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="kw">case</span> <span class="ch">&#39;u&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;x&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;X&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;o&#39;</span>:
                    result ~= <span class="st">&quot;isUnsigned,&quot;</span>; <span class="co">// unsigned integral</span>
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="kw">case</span> <span class="ch">&#39;f&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;F&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;e&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;E&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;g&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;G&#39;</span>:
                    result ~= <span class="st">&quot;isFloatingPoint,&quot;</span>; <span class="co">// floating point</span>
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="kw">case</span> <span class="ch">&#39;c&#39;</span>:
                    result ~= <span class="st">&quot;isSomeChar,&quot;</span>; <span class="co">// char</span>
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="kw">case</span> <span class="ch">&#39;s&#39;</span>:
                    result ~= <span class="st">&quot;isAnyType,&quot;</span>; <span class="co">// any string-convertible type</span>
                    afterPercent = <span class="kw">false</span>;
                    <span class="kw">break</span>;
                <span class="co">/* flags, width, */</span>
                <span class="kw">case</span> <span class="ch">&#39;+&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;-&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;#&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;.&#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39; &#39;</span>:
                <span class="kw">case</span> <span class="ch">&#39;0&#39;</span>:
                    ..
                <span class="kw">case</span> <span class="ch">&#39;9&#39;</span>:
                    <span class="kw">break</span>;
                <span class="kw">default</span>:
                    error = <span class="kw">true</span>; <span class="co">// Error!</span>
                    <span class="kw">break</span>;
            }
        }
        <span class="kw">else</span>
        {
            <span class="kw">if</span> (elem == <span class="ch">&#39;%&#39;</span>) afterPercent = <span class="kw">true</span>;
        }
    }

    <span class="co">// Get rid of the last comma:</span>
    <span class="kw">if</span> (result.<span class="dt">length</span> &gt; <span class="dv">17</span>) result = result[<span class="dv">0</span>..$-<span class="dv">1</span>];
    <span class="co">// finishing the alias code</span>
    result ~= <span class="st">&quot;) ArgsChecks;&quot;</span>;

    <span class="kw">if</span> (afterPercent <span class="co">// finished the string but still in &quot;afterPercent&quot; mode</span>
     || error)
        result = <span class="st">&quot;static assert(0, \&quot;Bad format string: \&quot; ~ a);&quot;</span>;

    <span class="kw">return</span> result;
}</code></pre>
<p>It's quite a long sample, but the logic behind it is straightforward: it iterates on all characters and looks for <code class="sourceCode d">%x</code> patterns. I included here a basic treatment for flags and such, but as I said earlier, this example does not deal with the entire POSIX specification: the goal is <em>not</em> to validate the formatting string, but to extract the formatters. When it determines the string is malformed, the generated code will be a <code class="sourceCode d"><span class="kw">static</span> <span class="kw">assert</span></code>.</p>
<p>So, at the end, we get ready-to-be-mixed-in strings, like these:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="co">// no formatter</span>
<span class="st">&quot;alias TypeTuple!() ArgsChecks;&quot;</span>

<span class="co">// the previous example</span>
<span class="st">&quot;alias TypeTuple!(isIntegral,isAnyType,isFloatingType) ArgsChecks;&quot;</span>

<span class="co">// Bad string</span>
<span class="st">&quot;static assert(0, \&quot;Bad format string: %s and %z\&quot;);&quot;</span></code></pre>
<p>Once the tuple of checks is done, we need a template that verifies each argument in turn with the corresponding template. To get a better error message, I use an <code class="sourceCode d"><span class="dt">int</span></code> template parameter, to count the number of args checked.</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> verifychecks;
<span class="kw">import</span> std.conv;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> std.typetuple;
<span class="kw">import</span> isanytype;
<span class="kw">import</span> getformatters;

<span class="kw">template</span> ArgsChecks(<span class="kw">alias</span> a) <span class="kw">if</span> (isSomeString!(<span class="dt">typeof</span>(a)))
{
    <span class="kw">mixin</span>(getFormatters(a));
}

<span class="kw">template</span> VerifyChecks(<span class="dt">int</span> which, Checks...)
{
    <span class="kw">template</span> on(Args...)
    {
        <span class="kw">static</span> <span class="kw">if</span> (Checks.<span class="dt">length</span> != Args.<span class="dt">length</span>)
            <span class="kw">static</span> <span class="kw">assert</span>( <span class="dv">0</span>
                         , <span class="st">&quot;ctwrite bad number of args: waited for &quot;</span>
                         ~ to!<span class="dt">string</span>(Checks.<span class="dt">length</span>)
                         ~ <span class="st">&quot; args, got &quot;</span>
                         ~ to!<span class="dt">string</span>(Args.<span class="dt">length</span>)
                         ~ <span class="st">&quot;.&quot;</span>);
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Checks.<span class="dt">length</span> == <span class="dv">0</span>) <span class="co">// end of process</span>
            <span class="kw">enum</span> on = <span class="kw">true</span>;
        <span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> ({ <span class="kw">alias</span> Checks[<span class="dv">0</span>] C; <span class="kw">return</span> C!(Args[<span class="dv">0</span>]);}()) <span class="co">// recurse</span>
            <span class="kw">enum</span> on = VerifyChecks!(which+<span class="dv">1</span>, Checks[<span class="dv">1</span>..$]).on!(Args[<span class="dv">1</span>..$]);
        <span class="kw">else</span>
            <span class="kw">static</span> <span class="kw">assert</span>( <span class="dv">0</span>
                         , <span class="st">&quot;cwrite bad arg: arg #&quot;</span>
                         ~ to!<span class="dt">string</span>(which)
                         ~ <span class="st">&quot; of type &quot;</span>
                         ~ Args[<span class="dv">0</span>].<span class="dt">stringof</span>
                         ~ <span class="st">&quot; does not verify check &quot;</span>
                         ~ __traits(identifier, Checks[<span class="dv">0</span>]));
    }
}</code></pre></td></tr></table>
<p>The <code class="sourceCode d">Verify</code> template is another example of a double-decker template, as seen in section <a href="#templates-in-templates">Templates In Templates</a>, to get a nice calling syntax:</p>
<pre class="sourceCode d"><code class="sourceCode d">Verify!(<span class="dv">0</span>, isIntegral, isFloatingPoint).on!(<span class="dt">int</span>, <span class="dt">double</span>)</code></pre>
<p>The most subtle part is on line 26:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> ({ <span class="kw">alias</span> Checks[<span class="dv">0</span>] C; <span class="kw">return</span> C!(Args[<span class="dv">0</span>]);}()) <span class="co">// recurse</span></code></pre>
<p>We want to apply the first checking constraint, <code class="sourceCode d">Check[<span class="dv">0</span>]</code>, on the first argument type, <code class="sourceCode d">Args[<span class="dv">0</span>]</code>. Alas, the D grammar does not allow the following construct:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Checks[<span class="dv">0</span>]!(Args[<span class="dv">0</span>])) <span class="co">// recurse</span></code></pre>
<p>The standard way to do this would be:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">alias</span> Checks[<span class="dv">0</span>] Check;
<span class="co">// and then</span>
<span class="kw">else</span> <span class="kw">static</span> <span class="kw">if</span> (Check!(Args[<span class="dv">0</span>]))</code></pre>
<p>But that would put a <code class="sourceCode d">Check</code> symbol in the template local scope (at one time this would have broken the eponymous trick). It'd be possible to define a <code class="sourceCode d">VerifyImpl</code> template (see section <a href="#impltrick">impltrick</a>), but using a local delegate works as well:</p>
<pre class="sourceCode d"><code class="sourceCode d">{ <span class="kw">alias</span> Checks[<span class="dv">0</span>] C; <span class="kw">return</span> C!(Args[<span class="dv">0</span>]);}()</code></pre>
<p>The <code>{...}</code> part defines the delegate and <code class="sourceCode d">()</code> calls it, returning either <code class="sourceCode d"><span class="kw">true</span></code> or <code class="sourceCode d"><span class="kw">false</span></code>. This is then inserted inside the <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>.</p>
<p>Anyway, once the checking code is done, the rest is easy:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> checkedwrite;
<span class="kw">import</span> std.stdio;
<span class="kw">import</span> std.traits;
<span class="kw">import</span> verifychecks;

<span class="dt">void</span> cwritef(<span class="kw">alias</span> a, Args...)(Args args)
<span class="kw">if</span> (isSomeString!(<span class="dt">typeof</span>(a))
 &amp;&amp; VerifyChecks!(<span class="dv">1</span>, ArgsChecks!(a)).on!(Args))
{
    writef(a, args);
}

<span class="dt">void</span> cwritefln(<span class="kw">alias</span> a, Args...)(Args args)
<span class="kw">if</span> (isSomeString!(<span class="dt">typeof</span>(a))
 &amp;&amp; VerifyChecks!(<span class="dv">1</span>, ArgsChecks!(a)).on!(Args))
{
    writefln(a, args);
}</code></pre>
<p>Usage is then as shown <a href="#statically-checked-writeln">here</a>.</p>
<h2 id="extending-a-class">Extending a Class</h2>
<blockquote>
<p><strong>TODO</strong> UFCS is now implemented. Things happened in 2012!</p>
</blockquote>
<p>There is regularly a wish in the D community for something called Universal Function Call Syntax (UFCS): the automatic transformation of <code class="sourceCode d">a.foo(b)</code> into <code class="sourceCode d">foo(a,b)</code> when <code>a</code> has no member called <code class="sourceCode d">foo</code> and there <em>is</em> a free function called <code class="sourceCode d">foo</code> in the local scope. This already works for arrays (hence, for strings) but not for other types.</p>
<p>There is no way to get that in D for built-in types except by hacking the compiler, but for user-defined types, you can call templates to the rescue.</p>
<p><code class="sourceCode d">opDispatch</code> can be used to forward to an external free function. A call <code class="sourceCode d"><span class="kw">this</span>.method(a,b)</code> becomes <code class="sourceCode d">method(</code><code class="sourceCode d"><span class="kw">this</span></code><code class="sourceCode d">,a,b)</code>.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> forwarder;

<span class="kw">mixin</span> <span class="kw">template</span> Forwarder()
{
    <span class="kw">auto</span> opDispatch(<span class="dt">string</span> name, Args...)(Args args)
    {
        <span class="kw">mixin</span>(<span class="st">&quot;return &quot;</span> ~ name ~ <span class="st">&quot;(args);&quot;</span>);
    }
}</code></pre>
<p>In D, a void <code class="sourceCode d"><span class="kw">return</span></code> clause is legal:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">return</span>;
<span class="co">// or return void;</span></code></pre>
<p>So if <code class="sourceCode d">name(<span class="kw">this</span>,a,b)</code> is a <code class="sourceCode d"><span class="dt">void</span></code>-returning function, all is OK.</p>
<p>The main limitation of this trick is that it doesn't work across modules boundaries. Too bad.</p>
<h2 id="pattern-matching-with-functions">Pattern Matching With Functions</h2>
<blockquote>
<p><strong>Unfinished</strong> The idea is to group a bunch of templates together and use their pattern matching ability. Maybe to be put in <a href="#function-templates">Function Templates</a>?</p>
</blockquote>
<h2 id="generating-a-switch-for-tuples">Generating a Switch for Tuples</h2>
<p>Case 0:, etc.</p>
<p>Or more generally, the idea to craft specific runtime code given compile-time information. See also <a href="#sorting-networks">Sorting Networks</a>.</p>
<h1 id="appendices">Appendices</h1>
<h2 id="the-is-expression">The <code>is</code> expression</h2>
<h3 id="general-syntax">General Syntax</h3>
<p>The <code class="sourceCode d"><span class="kw">is</span>(...)</code> expression gives you some compile-time introspection on types (and, as a side-effect, on D expressions). It's described <a href="http://www.dlang.org/expression.html#IsExpression">here</a> in the D website. This expression has a quirky syntax, but the basic use is very simple and it's quite useful in conjunction with <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> (see section <a href="#static-if">Static If</a>) and template constraints (see section <a href="#constraints">Constraints</a>). The common syntaxes are:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">is</span>( Type (optional identifier) )
<span class="kw">is</span>( Type (optional identifier) :  OtherType,
         (optional <span class="kw">template</span> parameters list) )
<span class="kw">is</span>( Type (optional identifier) == OtherType,
         (optional <span class="kw">template</span> parameters list) )</code></pre>
<p>If what's inside the parenthesis is valid (see below), <code class="sourceCode d"><span class="kw">is</span>()</code> returns <code class="sourceCode d"><span class="kw">true</span></code> at compile-time, else it returns <code class="sourceCode d"><span class="kw">false</span></code>.</p>
<h3 id="istype"><code>is(Type)</code></h3>
<p>Let's begin with the very first syntax: if <code class="sourceCode d">Type</code> is a valid D type in the scope of the <code class="sourceCode d"><span class="kw">is</span></code> expression, <code class="sourceCode d"><span class="kw">is</span>()</code> returns <code class="sourceCode d"><span class="kw">true</span></code>. As a bonus, inside a <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code>, the optional <code class="sourceCode d">identifier</code> becomes an alias for the type. For example:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> canbeinstantiated;

<span class="kw">template</span> CanBeInstantiatedWith(<span class="kw">alias</span> templateName, Types...)
{
    <span class="co">// is templateName!(Types) a valid type?</span>
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>( templateName!(Types) ResultType ))
    <span class="co">// here you can use ResultType (== templateName!(Types))</span>
        <span class="kw">alias</span> ResultType CanBeInstantiatedWith;
    <span class="kw">else</span>
        <span class="kw">alias</span> <span class="dt">void</span>       CanBeInstantiatedWith;
}</code></pre>
<p>Note that the previous code was done with templates in mind, but it is quite robust: if you pass as <code class="sourceCode d">templateName</code> something that's not a template name (a function name, for example), the <code class="sourceCode d"><span class="kw">is</span></code> will see <code class="sourceCode d">templateName!(Types)</code> has no valid type and will return <code class="sourceCode d"><span class="kw">false</span></code>. <code class="sourceCode d">CanBeInstantiatedWith</code> will correctly be set to <code class="sourceCode d"><span class="dt">void</span></code> and your program does not crash.</p>
<blockquote>
<p><strong>Testing for an alias</strong> Sometimes you do not know if the template argument you received is a type or an alias (for example, when dealing with tuples elements). In that case, you can use <code class="sourceCode d">!<span class="kw">is</span>(symbol)</code> as a test. If it really is an alias and not a type, this will return <code class="sourceCode d"><span class="kw">true</span></code>.}</p>
</blockquote>
<p>An interesting use for this form of <code class="sourceCode d"><span class="kw">is</span></code>, is testing whether or not some D code is valid. Consider: D blocks are seen as delegates by the compiler (Their type is <code class="sourceCode d"><span class="dt">void</span> <span class="kw">delegate</span>()</code>). Using this in conjunction with <code class="sourceCode d"><span class="dt">typeof</span></code> let you test the validity of a block statement: if <code class="sourceCode d">some code</code> is valid, <code class="sourceCode d"><span class="dt">typeof</span>({ some code }())</code> (note the <code class="sourceCode d">()</code> at the end of the delegate to 'activate' it) has a real D type and <code class="sourceCode d"><span class="kw">is</span></code> will return true.</p>
<p>Let's put this to some use. Imagine you have a function template <code class="sourceCode d">fun</code> and some arguments, but you do not know if <code class="sourceCode d">fun</code> can be called with this particular bunch of arguments. If it's a common case in your code, you should abstract it as a template. Let's call it <code class="sourceCode d">validCall</code> and make it a function template also, to easily use it with the arguments:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> validcall;
<span class="kw">import</span> std.conv;

<span class="dt">bool</span> validCall(<span class="kw">alias</span> fun, Args...)(Args args)
{
    <span class="kw">return</span> <span class="kw">is</span>( <span class="dt">typeof</span>({ <span class="co">/* code to test */</span>
                        fun(args);
                        <span class="co">/* end of code to test */</span>
                      }()));
}

<span class="co">// Usage:</span>
T add(T)(T a, T b) { <span class="kw">return</span> a+b;}
<span class="dt">string</span> conc(A,B)(A a, B b) { <span class="kw">return</span> to!<span class="dt">string</span>(a) ~ to!<span class="dt">string</span>(b);}

<span class="dt">void</span> main()
{
    <span class="kw">assert</span>( validCall!add(<span class="dv">1</span>, <span class="dv">2</span>));   <span class="co">// generates add!(int)</span>
    <span class="kw">assert</span>(!validCall!add(<span class="dv">1</span>, <span class="st">&quot;abc&quot;</span>)); <span class="co">// no template instantiation possible</span>

    <span class="kw">assert</span>( validCall!conc(<span class="dv">1</span>, <span class="st">&quot;abc&quot;</span>)); <span class="co">// conc!(int, string) is OK.</span>
    <span class="kw">assert</span>(!validCall!conc(<span class="dv">1</span>)       ); <span class="co">// no 1-argument version for conc</span>

    <span class="kw">struct</span> S {}

    <span class="kw">assert</span>(!validCall!S(<span class="dv">1</span>, <span class="fl">2.3</span>)); <span class="co">// S is not callable</span>
}</code></pre>
<p>Note that the tested code is simply `<code class="sourceCode d">fun(args);</code>'. That is, there is no condition on <code class="sourceCode d">fun</code>'s type: it could be a function, a delegate or even a struct or class with <code class="sourceCode d">opCall</code> defined. There are basically two ways <code class="sourceCode d">fun(args);</code> can be invalid code: either <code class="sourceCode d">fun</code> is not callable as a function, or it is callable, but <code class="sourceCode d">args</code> are not valid arguments.</p>
<p>By the way, fun as it may be to use this trick, D provides you with a cleaner way to test for valid compilation:</p>
<pre class="sourceCode d"><code class="sourceCode d">__traits(compiles, { <span class="co">/* some code */</span> })</code></pre>
<p><code class="sourceCode d">__traits</code> is another of D numerous Swiss Army knife constructs. You can find the <code class="sourceCode d">compiles</code> documentation <a href="http://www.dlang.org/traits.html#compiles">here</a>. Section <a href="#traits"><code>__traits</code></a> is dedicated to it.</p>
<h3 id="istype-anothertype-and-istype-anothertype"><code>is(Type : AnotherType)</code> and <code>is(Type == AnotherType)</code></h3>
<p>The two other basic forms of <code class="sourceCode d"><span class="kw">is</span></code> return true if <code class="sourceCode d">Type</code> can be implicitly converted to (is derived from) <code class="sourceCode d">AnotherType</code> and if <code class="sourceCode d">Type</code> is exactly <code class="sourceCode d">AnotherType</code>, respectively. I find them most interesting in their more complex form, with a list of template parameters afterwards. In this case, the template parameters act a bit as type variables in an equation. Let me explain:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">is</span>(Type identifier == SomeComplexTypeDependingOnUAndV, U, V)</code></pre>
<p>The previous code really means: 'excuse me, Mr. D Compiler, but is <code class="sourceCode d">Type</code> perchance some complex type depending on <code>U</code> and <code>V</code> for some <code>U</code> and <code>V</code>? If yes, please give me those.' For example:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> ArrayElement(T)
{
    <span class="co">// is T an array of U, for some U?</span>
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T t : U[], U))
        <span class="kw">alias</span> U ArrayElement; <span class="co">// U can be used, let&#39;s expose it</span>
    <span class="kw">else</span>
        <span class="kw">alias</span> <span class="dt">void</span> ArrayElement;
}

<span class="kw">template</span> isAssociativeArray(AA)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>( AA aa == Value[Key], Value, Key))
        <span class="co">/* code here can use Value and Key,</span>
<span class="co">           they have been deduced by the compiler. */</span>
    <span class="kw">else</span>
        <span class="co">/* AA is not an associative array</span>
<span class="co">          Value and Key are not defined. */</span>
}</code></pre>
<p>Strangely, you can only use it with the <code class="sourceCode d"><span class="kw">is</span>(Type identifier, ...)</code> syntax: you <em>must</em> have <code class="sourceCode d">identifier</code>. The good new is, the complex types being inspected can be templated types and the parameter list can be any template parameter: not only types, but integral values,... For example, suppose you do what everybody does when encountering D templates: you create a templated n-dimensional vector type.</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">struct</span> Vector(Type, <span class="dt">int</span> dim) { ... }</code></pre>
<p>If you did not expose <code class="sourceCode d">Type</code> and <code class="sourceCode d">dim</code> (as aliases for example, as seen in sections <a href="#inner-alias">Inner Alias</a> and <a href="#giving-access-to-inner-parameters">Giving Access to Inner Parameters</a>), you can use <code class="sourceCode d"><span class="kw">is</span></code> to extract them for you:</p>
<pre class="sourceCode d"><code class="sourceCode d">Vector!( ?, ?) myVec;
<span class="co">// is myVec a vector of ints, of any dimension?</span>
<span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(<span class="dt">typeof</span>(myVec) mv == Vector!(<span class="dt">int</span>, dim), dim))

<span class="co">// is it a 1-dimensional vector?</span>
<span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(<span class="dt">typeof</span>(myVec) mv == Vector!(T, <span class="dv">1</span>), T))</code></pre>
<blockquote>
<p><strong>is( A != B)?</strong> No, sorry, this doesn't exist. Use <code class="sourceCode d"><span class="kw">is</span>(A == B)</code>. But beware this will also fire if <code>A</code> or <code>B</code> are not legal types (which makes sense: if <code>A</code> is not defined, then by definition it cannot be equal to <code>B</code>). If necessary, you can use <code class="sourceCode d"><span class="kw">is</span>(A) &amp;&amp; <span class="kw">is</span>(B) &amp;&amp; !<span class="kw">is</span>(A == B)</code>.</p>
</blockquote>
<blockquote>
<p><strong>is A a supertype to B?</strong> Hey, <code class="sourceCode d"><span class="kw">is</span>(MyType : SuperType)</code> is good to know if <code class="sourceCode d">MyType</code> is a subtype to <code class="sourceCode d">SuperType</code>. How do I ask if <code class="sourceCode d">MyType</code> is a supertype to <code class="sourceCode d">SubType</code>? Easy, just use <code class="sourceCode d"><span class="kw">is</span>(SubType : MyType)</code>.</p>
</blockquote>
<p>For me, the main limitation is that template tuple parameters are not accepted. Too bad. See, imagine you use <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> a lot. At one point, you need a template to test if something is a <code class="sourceCode d">Tuple!(T...)</code> for some <code>T</code> which can be 0 or more types. Though luck, <code class="sourceCode d"><span class="kw">is</span></code> is a bit of a letdown there, as you cannot do:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">template</span> isTuple(T)
{
    <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(T tup == Tuple!(InnerTypes), InnerTypes...)
(...)                                          ^^^^^^^^^^^^^</code></pre>
<blockquote>
<p><strong>TODO</strong> Yes you can! This was changed in DMD 2.060. This section needs updating!</p>
</blockquote>
<p>But sometimes D channels its inner perl and, lo! There is more than one way to do it! You can use <a href="#ifti">IFTI</a> and our good friend the <code class="sourceCode d"><span class="kw">is</span>(<span class="dt">typeof</span>({...}()))</code> expression there. You can also use <code class="sourceCode d">__traits</code>, depending on you mood, but since this appendix is specifically on <code class="sourceCode d"><span class="kw">is</span></code>:</p>
<table class="sourceCode d numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="sourceCode"><pre><code class="sourceCode d"><span class="kw">module</span> istuple;
<span class="kw">import</span> std.typecons;

<span class="kw">template</span> isTuple(T)
{
    <span class="kw">enum</span> <span class="dt">bool</span> isTuple =
        <span class="kw">is</span>(<span class="dt">typeof</span>({
            <span class="dt">void</span> tupleTester(InnerTypes...)(Tuple!(InnerTypes) tup) {}
            T.<span class="dt">init</span> possibleTuple;
            tupleTester(possibleTuple);
        }()));
}</code></pre></td></tr></table>
<p>Line 8 defines the function template <code class="sourceCode d">tupleTester</code>, that only accepts <code class="sourceCode d">Tuple</code>s as arguments (even though it does nothing with them). We create something of type <code>T</code> on line 9, using the <code class="sourceCode d">.<span class="dt">init</span></code> property inherent in all D types, and try to call <code class="sourceCode d">tupleTester</code> with it. If <code>T</code> is indeed a <code class="sourceCode d">Tuple</code> this entire block statement is valid, the resulting delegate call indeed has a type and <code class="sourceCode d"><span class="kw">is</span></code> returns <code class="sourceCode d"><span class="kw">true</span></code>.</p>
<p>There are two things to note here: first, <code class="sourceCode d">isTuple</code> works for any templated type called <code class="sourceCode d">Tuple</code>, not only <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a>. If you want to restrict it, change <code class="sourceCode d">tupleTester</code> definition. Secondly, we do not get access to the inner types this way. For <a href="http://dlang.org/phobos/std_typecons.html#Tuple">std.typecons.Tuple</a> it's not really a problem, as they can be accessed with the <code class="sourceCode d">someTuple.Types</code> alias, but still...</p>
<p>By the way, the template parameter list elements can themselves use the <code class="sourceCode d">A : B</code> or <code class="sourceCode d">A == B</code> syntax:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>( T t == A!(U,V), U : SomeClass!W, V == <span class="dt">int</span>[n], W, <span class="dt">int</span> n))</code></pre>
<p>This will be OK if <code>T</code> is indeed an <code>A</code> instantiated with an <code>U</code> and a <code>V</code>, themselves verifying that this <code>U</code> is derived from <code class="sourceCode d">SomeClass!W</code> for some <code>W</code> type and that <code>V</code> is a static array of <code class="sourceCode d"><span class="dt">int</span></code>s of length <code>n</code> to be determined (and possibly used afterwards). In the if branch of the <code class="sourceCode d"><span class="kw">static</span> <span class="kw">if</span></code> <code>U</code>, <code>V</code>, <code>W</code> and <code>n</code> are all defined.</p>
<h3 id="type-specializations">Type Specializations</h3>
<p>There is a last thing to know about <code class="sourceCode d"><span class="kw">is</span></code>: with the <code class="sourceCode d"><span class="kw">is</span>(Type (identifier) == Something)</code> version, <code class="sourceCode d">Something</code> can also be a type specialization, one of the following D keywords: <code class="sourceCode d"><span class="kw">function</span></code>, <code class="sourceCode d"><span class="kw">delegate</span></code>, <code class="sourceCode d"><span class="kw">return</span></code>, <code class="sourceCode d"><span class="kw">struct</span></code>, <code class="sourceCode d"><span class="kw">enum</span></code>, <code class="sourceCode d"><span class="kw">union</span></code>, <code class="sourceCode d"><span class="kw">class</span></code>, <code class="sourceCode d"><span class="kw">interface</span></code>, <code class="sourceCode d"><span class="kw">super</span></code>, <code class="sourceCode d"><span class="kw">const</span></code>, <code class="sourceCode d"><span class="kw">immutable</span></code> or <code class="sourceCode d">shared</code>. The condition is satisfied if <code class="sourceCode d">Type</code> is one of those (except for <code class="sourceCode d"><span class="kw">super</span></code> and <code class="sourceCode d"><span class="kw">return</span></code>, see below). <code class="sourceCode d">identifier</code> then becomes an alias for some property of <code class="sourceCode d">Type</code>, as described in the following table.</p>
<table>
<caption>Effect of type specializations in <code>is</code></caption>
<thead>
<tr class="header">
<th align="left">Specialization</th>
<th align="left">Satisfied if</th>
<th align="left"><code>identifier</code> becomes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><code>function</code></td>
<td align="left"><code>Type</code> is a function</td>
<td align="left">The function parameters type tuple</td>
</tr>
<tr class="even">
<td align="left"><code>delegate</code></td>
<td align="left"><code>Type</code> is a delegate</td>
<td align="left">The delegate function type</td>
</tr>
<tr class="odd">
<td align="left"><code>return</code></td>
<td align="left"><code>Type</code> is a function</td>
<td align="left">The return type</td>
</tr>
<tr class="even">
<td align="left"><code>return</code></td>
<td align="left"><code>Type</code> is a delegate</td>
<td align="left">The return type</td>
</tr>
<tr class="odd">
<td align="left"><code>struct</code></td>
<td align="left"><code>Type</code> is a struct</td>
<td align="left">The struct type</td>
</tr>
<tr class="even">
<td align="left"><code>enum</code></td>
<td align="left"><code>Type</code> is an enum</td>
<td align="left">The enum base type</td>
</tr>
<tr class="odd">
<td align="left"><code>union</code></td>
<td align="left"><code>Type</code> is an union</td>
<td align="left">The union type</td>
</tr>
<tr class="even">
<td align="left"><code>class</code></td>
<td align="left"><code>Type</code> is a class</td>
<td align="left">The class type</td>
</tr>
<tr class="odd">
<td align="left"><code>interface</code></td>
<td align="left"><code>Type</code> is an interface</td>
<td align="left">The interface type</td>
</tr>
<tr class="even">
<td align="left"><code>super</code></td>
<td align="left"><code>Type</code> is a class</td>
<td align="left">The type tuple (Base Class, Interfaces)</td>
</tr>
<tr class="odd">
<td align="left"><code>const</code></td>
<td align="left"><code>Type</code> is const</td>
<td align="left">The type</td>
</tr>
<tr class="even">
<td align="left"><code>immutable</code></td>
<td align="left"><code>Type</code> is immutable</td>
<td align="left">The type</td>
</tr>
<tr class="odd">
<td align="left"><code>shared</code></td>
<td align="left"><code>Type</code> is shared</td>
<td align="left">The type</td>
</tr>
</tbody>
</table>
<p>Let's put that to some use: we want a factory template that will create a new struct or a new class, given its name as a template parameter:</p>
<pre class="sourceCode d"><code class="sourceCode d"><span class="kw">module</span> maker;
<span class="kw">import</span> std.algorithm;
<span class="kw">import</span> std.conv;

<span class="kw">template</span> make(A)
    <span class="kw">if</span> (<span class="kw">is</span>(A a == <span class="kw">class</span> )
     || <span class="kw">is</span>(A a == <span class="kw">struct</span>))
{
    <span class="kw">auto</span> make(Args...)(Args args)
    {
        <span class="kw">static</span> <span class="kw">if</span> (<span class="kw">is</span>(A a == <span class="kw">class</span>))
            <span class="kw">return</span> <span class="kw">new</span> A(args);
        <span class="kw">else</span>
            <span class="kw">return</span> A(args);
    }
}

<span class="kw">struct</span> S {<span class="dt">int</span> i;}
<span class="kw">class</span> C
{
    <span class="dt">int</span> i;
    <span class="kw">this</span>(<span class="dt">int</span> ii) { i = ii;}
    <span class="kw">override</span> <span class="dt">string</span> toString() @property
    {
        <span class="kw">return</span> <span class="st">&quot;C(&quot;</span>~to!<span class="dt">string</span>(i)~<span class="st">&quot;)&quot;</span>;
    }
}

<span class="dt">void</span> main()
{
    <span class="kw">auto</span> array = [<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>];

    <span class="kw">auto</span> structRange = map!( make!S )(array);
    <span class="kw">auto</span> classRange  = map!( make!C )(array);

     <span class="kw">assert</span>(equal(structRange, [S(<span class="dv">0</span>), S(<span class="dv">1</span>), S(<span class="dv">2</span>), S(<span class="dv">3</span>)]));
    <span class="kw">assert</span>(classRange.front.toString == <span class="st">&quot;C(0)&quot;</span>);
}</code></pre>
<p>You can find another example of this kind of <code class="sourceCode d"><span class="kw">is</span></code> in section <a href="#class-templates">Class Templates</a>, with the <code class="sourceCode d">duplicator</code> template.</p>
<h2 id="resources-and-further-reading">Resources and Further Reading</h2>
<blockquote>
<p><strong>Unfinished</strong> Any new resource welcome!</p>
</blockquote>
<p>Being a relatively young language, D doesn't have dozens of books or online sites dedicated to its learning. Still, there are a few resources on the Internet that pertains to D templates and associated subjects.</p>
<h3 id="d-templates">D Templates</h3>
<p>Here are some resources on D templates.</p>
<h4 id="d-reference">D Reference</h4>
<p>Your first stop should be the <a href="http://dlang.org">dlang.org</a> pages on templates. They are quite easy to read, don't hesitate to peruse them and bother the authors if anything is unclear or blatantly false. The <code class="sourceCode d">dlang.org</code> website is also a github project, <a href="https://github.com/D-Programming-Language/d-programming-language.org">here</a>. The following table lists the pages dealing with templates.</p>
<table>
<caption>pages dealing with templates</caption>
<thead>
<tr class="header">
<th align="left">Subject</th>
<th align="left">URL</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">The general page on templates</td>
<td align="left"><a href="http://dlang.org/template.html">template.html</a></td>
</tr>
<tr class="even">
<td align="left">D templates vs C++ ones</td>
<td align="left"><a href="http://dlang.org/templates-revisited.html">templates-revisited.html</a></td>
</tr>
<tr class="odd">
<td align="left">An article on tuples</td>
<td align="left"><a href="http://dlang.org/tuple.html">tuple.html</a></td>
</tr>
<tr class="even">
<td align="left">Template tuple parameters</td>
<td align="left"><a href="http://dlang.org/variadic-function-templates.html">variadic-function-templates.html</a></td>
</tr>
<tr class="odd">
<td align="left">Template constraints</td>
<td align="left"><a href="http://dlang.org/concepts.html">concepts.html</a></td>
</tr>
<tr class="even">
<td align="left">Mixin Templates</td>
<td align="left"><a href="http://dlang.org/template-mixin.html">template-mixin.html</a></td>
</tr>
<tr class="odd">
<td align="left">A small article on string mixins</td>
<td align="left"><a href="http://dlang.org/mixin.html">mixin.html</a></td>
</tr>
<tr class="even">
<td align="left"><code>static if</code></td>
<td align="left"><a href="http://dlang.org/version.html#staticif">version.html</a></td>
</tr>
<tr class="odd">
<td align="left"><code>is</code></td>
<td align="left"><a href="http://dlang.org/expression.html#IsExpression">expression.html</a></td>
</tr>
<tr class="even">
<td align="left">Type Aliasing</td>
<td align="left"><a href="http://dlang.org/declaration.html#alias">declaration.html</a></td>
</tr>
<tr class="odd">
<td align="left">Operator Overloading</td>
<td align="left"><a href="http://dlang.org/operatoroverloading.html">operatoroverloading.html</a></td>
</tr>
</tbody>
</table>
<h4 id="the-d-programming-language">The D Programming Language</h4>
<p>The main D book as of this writing is of course <code>The D Programming Language</code> (also known as <code>TDPL</code>), by Andrei Alexandrescu. It's a very good reference book, and fun to read too. TDPL has a very interesting approach to templates: Andrei first introduces them as a natural extension of functions, classes, and structs syntax, to get parametrized code. It's only afterwards that templates-as-scopes are introduced. The following table lists the chapters that deals with templates.</p>
<table>
<caption>TDPL Chapters Dealing With Templates</caption>
<thead>
<tr class="header">
<th align="left">Subject</th>
<th align="left">Chapter</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">Functions Templates</td>
<td align="left">5.3, 5.4, 5.10, and 5.12</td>
</tr>
<tr class="even">
<td align="left">Classes Templates</td>
<td align="left">6.14</td>
</tr>
<tr class="odd">
<td align="left">Struct Templates</td>
<td align="left">7.1.10</td>
</tr>
<tr class="even">
<td align="left"><code>alias</code></td>
<td align="left">7.4</td>
</tr>
<tr class="odd">
<td align="left">General Templates</td>
<td align="left">7.5</td>
</tr>
<tr class="even">
<td align="left">Mixin Templates</td>
<td align="left">7.6</td>
</tr>
<tr class="odd">
<td align="left">Operator Overlaoding</td>
<td align="left">12</td>
</tr>
</tbody>
</table>
<h3 id="programming-in-d">Programming in D</h3>
<p>Another quite interesting book is the translation from Turkish of Ali Cehreli's book <code>Programming in D</code>, which you can find for free here: <a href="http://ddili.org/ders/d.en/index.html">http://ddili.org/ders/d.en/index.html</a>. More precisely, as far as this document is concerned, the chapter on templates is already translated and can be found at <a href="http://ddili.org/ders/d.en/templates.html">http://ddili.org/ders/d.en/templates.html</a>. Ali's book aims to be a gentle introduction to D, so the rhythm is less gung ho than TDPL. If you do not want to read the present document, the previously linked chapter is your best bet as a template tutorial.</p>
<h3 id="the-d-wiki">The D Wiki</h3>
<p>Apart from books, the D wiki has a tutorial on templates that can be found at <a href="http://wiki.dlang.org/Introduction_to_D_templates">http://wiki.dlang.org/Introduction_to_D_templates</a>, that explains <a href="http://dlang.org/phobos/std_functional.html#unaryFun">std.functional.unaryFun</a> very thoroughly, dealing in passing with various subjects such as templates, string mixins, and instantiation scope. I found it a very pleasant read and a nice explanation of a difficult part of Phobos.</p>
<h3 id="d-metaprogramming">D Metaprogramming</h3>
<p>I found Nick Sabalausky's article at <a href="http://www.semitwist.com/articles/EfficientAndFlexible/SinglePage/">http://www.semitwist.com/articles/EfficientAndFlexible/SinglePage/</a> to be a very good read, and full of nifty ideas. In particular, Nick shows how to use compile-time information to craft code such that runtime arguments can then be used to ``influence'' compile-time values. Yes you read that right, and my description does not do it justice: <a href="http://www.semitwist.com/articles/EfficientAndFlexible/SinglePage/#part6-3">read on</a>, and see for yourselves. I definitely <em>must</em> put a section somewhere in this doc on this.</p>
<p>The code shown in the article can be found in a github project, at </p>
<h3 id="templates-in-other-languages">Templates in Other Languages</h3>
<blockquote>
<p><strong>Unfinished</strong> C++ templates, obviously. Articles, online books, and such. A small text on Boost. Also, maybe Java and C# generics.</p>
</blockquote>

<blockquote>
<p><strong>Unfinished</strong> Haskell and ML concerning types. In general, any type trick that Haskellers live by: encoding information in types, using types to forbid unwanted states and so on.</p>
</blockquote>


<blockquote>
<p><strong>Unfinished</strong> Maybe Lisp / Scheme / Clojure macros. Nemerle macros too.</p>
</blockquote>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>The <a href="http://www.boost.org">Boost</a> C++ library collection makes heavy use of templates.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>It's <em>both</em> an statement and a declaration, so I'll call it a construct.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Except for the degenerate, <span class="math"><em>n</em> = 0</span> case, since the identity function defined above accepts only one arg. A version with more than one argument is possible, but would need to return a tuple.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>I cheated a little bit there, because the resulting function accepts any number of arguments of any type, though the standard function parameters checks will stop anything untowards to happen. A cleaner (but longer, and for template functions, more complicated) implementation would propagate the initial function parameter typetuple.<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>See the example in section <a href="#named-fields-tuples">Named Field Tuples</a> for a way to extend Phobos <code>tuple</code>.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>The difference with Phobos <code>map</code> is that our version isn't lazy.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>Technically, <a href="http://dlang.org/phobos/std_algorithm.html#reduce">std.algorithm.reduce</a> is a <em>left fold</em>, while what is shown here is a <em>right fold</em>. The difference is not essential here.<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>Except, maybe, by having an interface template be empty for certain parameters, thus in effect disappearing from the list.<a href="#fnref8">↩</a></p></li>
<li id="fn9"><p>Ranges are overdue a tutorial.<a href="#fnref9">↩</a></p></li>
<li id="fn10"><p><code>bool</code> is a type with <em>two</em> values (<code>true</code> and <code>false</code>). <code>()</code>, the empty tuple, is the type that has only <em>one</em> value. And <code>void</code> is the type that has <em>no</em> value.<a href="#fnref10">↩</a></p></li>
<li id="fn11"><p>This was written in January 2012, let see when we get multiple alias this.<a href="#fnref11">↩</a></p></li>
<li id="fn12"><p>FWIW, on my computer, the cut-off seems to be for about 38-39 elements.<a href="#fnref12">↩</a></p></li>
<li id="fn13"><p>As with any other affirmation in this document, readers should feel free to prove me wrong. That shouldn't be too difficult.<a href="#fnref13">↩</a></p></li>
<li id="fn14"><p>If someone finds a way to determine with a template that <code>b</code> imports <code>std.algorithm</code>, I'd be delighted to see how it's done!<a href="#fnref14">↩</a></p></li>
<li id="fn15"><p>For those of you curious about it, they are named <code>__unittestXXX</code> where <code>XXX</code> is a number. Their type is more or less <code>void delegate()</code>.<a href="#fnref15">↩</a></p></li>
<li id="fn16"><p>I didn't try static constructors in modules. Don't hesitate to play with them and tell me what happens.<a href="#fnref16">↩</a></p></li>
<li id="fn17"><p>Maybe by using the <code>qualifiedName</code> template shown in section <a href="#parent">parent</a>.<a href="#fnref17">↩</a></p></li>
<li id="fn18"><p>If you came here to see a way to get all parents of a class, see section <a href="#class-hierarchy">Class Hierarchy</a>.<a href="#fnref18">↩</a></p></li>
<li id="fn19"><p>In fact, it's the mother of all operations on sequences, since map and filter can be defined using reduce.<a href="#fnref19">↩</a></p></li>
<li id="fn20"><p>from Haskell Curry, who formalized the idea.<a href="#fnref20">↩</a></p></li>
<li id="fn21"><p>A standard generalization would be a template taking on type in <span class="math"><em>n</em></span>: <code>Stride!(3, T0, T1, ..., Tn)</code>. I let that as an exercise to the reader.<a href="#fnref21">↩</a></p></li>
</ol>
</div>
